At the moment all the console.log following the .then, execute at the same time.
I want every .then to wait for the previous one, how can I do it?
function doIt(sentence) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(console.log(sentence))
}, 2000)
})
}
doIt('Place order')
.then(() => setTimeout(() => { console.log('Cut the fruit') }, 2000))
.then(() => setTimeout(() => { console.log('Add water and ice') }, 2000))
.then(() => setTimeout(() => { console.log('Start the machine') }, 2000))
.then(() => setTimeout(() => { console.log('Select topping') }, 2000))
.then(() => setTimeout(() => { console.log('Serve the ice cream') }, 2000))
>Solution :
You have to create a promise chain.
function doIt(sentence) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(console.log(sentence)), 2000);
});
}
doIt("Place order")
.then(() => doIt("Cut the fruit"))
.then(() => doIt("Add water and ice"))
.then(() => doIt("Start the machine"))
.then(() => doIt("Select topping"))
.then(() => doIt("Serve the ice cream"));