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.