Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript promise, all the .then execute at the same time

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading