I have 5 promises I want to put in a specific order. But I have struggled a lot with finding a way to put them in the correct order. I have tried the following, resulting in a order of (1-2)-5-(3-4) instead of (1-2)-(3-4)-5, or (3-4)-(1-2)-5 (also OK). So the 5th comes too early, it should come last. I have tried to put 1+2+3+4 in an array/list as you can see below, and then creating the 5th promise, telling it to wait for the execution of 1-4. But the order turnes out incorrectly, as said... Any ideas?
this.promises.push(PROMISE1.then(() => {
**Code for PROMISE 1**
this.promises.push(PROMISE2.then(() => {
**Code for PROMISE 2**
})
);
}));
this.promises.push(PROMISE3.then(() => {
**Code for PROMISE 3**
this.promises.push(PROMISE4).then(() => {
**Code for PROMISE 4**
})
);
}));
Promise.all(this.promises).then(() => {
**Code for PROMISE 5**
});
Instead of pushing in the callback for each promise, return the inner promise.
var promises = [];
promises.push(method1().then(() => { return method2().then(() => { } });
promises.push(method3().then(() => { return method4().then(() => { } });
Promise.all(promises).then(() => { ... });
Here's a working sample:
function delay(time, name) { console.log("running", name); return new Promise(r => setTimeout(r, time)); } var promises = []; promises.push(delay(1000, "1").then(() => { console.log("1 inner"); return delay(500, "1 inner").then(() => console.log("1 inner most")); })); promises.push(delay(250, "2").then(() => { console.log("2 inner"); return delay(1000, "2 inner").then(() => console.log("2 inner most")); })); Promise.all(promises).then(() => console.log("all done!"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.