1
function first(){
    console.log("1")
}

function second(){
     new Promise ((resolve,reject)=>{
        setTimeout(function(){
            console.log("2")
            resolve();
        } ,0);

     })  
}

function third(){
    console.log("3")
}

 async function run(){
   
    first();
    await second();
    third();

}

run();

Need to make the function call sync to get final output as 1,2,3 i tried creating the promise and use async await but that didnt help any other way

Swarup Chavan
  • 206
  • 1
  • 15
  • Does this answer your question? [Combination of async function + await + setTimeout](https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout) – Robo Robok Aug 07 '20 at 12:49
  • What does this resolve(...) do? And what is your actual task? What are you expected to do here? Change the run method so it would print them in order? Or what? – Arek Bal Aug 07 '20 at 12:53
  • Where does this `resolve` come from, and what does it do? – Bergi Aug 07 '20 at 12:53
  • @Bergi have updated the question sorry it was my mistake – Swarup Chavan Aug 07 '20 at 12:58
  • @SwarupChavan Thanks, that's making a lot more sense now. The only problem is that you forgot to `return` the created promise from the `second` function, so you're `await`ing `undefined`. – Bergi Aug 07 '20 at 13:00

1 Answers1

3

Pack the setTimeout into a promise and resolve in setTimeout,

Use async await for that promise in order for that to run consecutively

function first() {
  console.log("1")
}

function second() {
  return new Promise(res => {
    setTimeout(function() {
      console.log("2");
      res()
    }, 0)
  })

}

function third() {
  console.log("3")
}

async function run() {

  first();
  await second()
  third();
}

run();
EugenSunic
  • 13,162
  • 13
  • 64
  • 86