I currently have a few functions that return promises such as the below:
function action_one(){
return new Promise((resolve, reject)->{
...
});
}
I want to be able to wait on one before doing the next promise without nesting them. I had searched for some solutions, one being PromiseAll() but it does not seem to do it in order. Another solution was to do the following:
promise.then(result =>{
action
}.then(result =>{
action
}.then(result =>{
action
}.then(result =>{
action
}.then(result =>{ etc.
which I'm not sure works for my issue but it doesn't seem compactable.
what would be best practice in this situation?
Edit:
I'm not sure how to use the .then chain with multiple promises such as:
promise.then(result =>{
action
}promise.then(result =>{
action
}promise.then(result =>{
action
}promise.then(result =>{
action
}promise.then(result =>{ etc.
It does not yield the result I expect
CodePudding user response:
I found my solution:
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000);
}).then(function(result) {
alert(result); // 1
return new Promise((resolve, reject) => { // (*)
setTimeout(() => resolve(result * 2), 1000);
});
}).then(function(result) { // (**)
alert(result); // 2
return new Promise((resolve, reject) => {
setTimeout(() => resolve(result * 2), 1000);
});
}).then(function(result) {
alert(result); // 4
});
I needed to return the promise to chain them which is why it was not working. Source: https://javascript.info/promise-chaining
CodePudding user response:
How about using async/await so you will have synchronous function