function promise1 (num) {
return new Promise(resolve1 => {
let timeout = Math.random() * 5000
setTimeout(() => {
console.log(num)
resolve1()
}, timeout)
})
}
let promiseVar = promise1(0)
for (let i = 1; i < 5; i++) {
promiseVar.then(() => {
promiseVar = promise1(i)
})
}
I've got a function that creates a promise that might take an arbitrary amount of time to complete but I want the promises executed in a specific order. Inside the for loop I expect it to only begin the next promise after the previous one has resolved but the console logs the numbers in a random order as if it starts each promise before the last one has resolved. Is there a better way to execute a series of promises like this or have I overlooked something.
You can set promiseVar
to the promise that results from then()
in the loop. This will have the effect of changing the promises:
function promise1(num) {
return new Promise(resolve1 => {
let timeout = Math.random() * 1000
setTimeout(() => {
console.log(num)
resolve1()
}, timeout)
})
}
let promiseVar = promise1(0)
for (let i = 1; i < 5; i++) {
promiseVar = promiseVar.then(() => promise1(i))
}
This will create all the promises, but it will leave the last one without a then. You can use promiseVar.then()
outside the loop to know when the last promise has resolved.