Change the execution order in JavaScript

Viewed 367

I have the below code

function run(){
    one();
    two();
    three();
}

function one(){
    console.log(1);
}

function two(){
    setTimeout(function(){
        console.log(2);
    });
}

function three(){
    console.log(3);
}

run(); 

The Output of the following code will be 1,3,2

What are the changes we have to do in a code so that output will be 1,2,3 ?

4 Answers

This should work:

async function run() {
    await one();
    await two()
    await three()
}


function one() {
    Promise.resolve(
        console.log(1)
    )
}

function two() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(2);
            resolve();
        });
    });


}

function three() {
    Promise.resolve(
        console.log(3)
    )
}

run(); 

Realise that three is called immediately after two. If you want three to only be called once the setTimeout inside two expires, then you should call three in that setTimeout callback.

To achieve that, you can pass an argument to two:

function run() {
  one();
  two(three); // Tell "two" what to call when its timer expires
}

function one() {
  console.log(1);
}

function two(callback) { // <-- callback argument
  setTimeout(function() {
    console.log(2);
    callback(); // <---
  })
}

function three() {
  console.log(3);
}

run();

Promises

Once you start using setTimeout to chain several asynchronous pieces of code, you will soon get into what is a "callback hell".

So for completeness, here is an implementation using the modern async/await syntax for using promises:

// Generic helper function
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function run() {
  one();
  await two();
  three();
}

function one() {
  console.log(1);
}

async function two() {
  await delay(0); // So to have the timeout involved...
  console.log(2);
}

function three() {
  console.log(3);
}

run();

you can use promise

function run(){
one();
two().then(three)

}


function one(){
console.log(1);
}

function two(){
  return new Promise((resolve , reject) => {
    setTimeout(function(){
    console.log(2);
    resolve()
    })
  })

}



function three(){

console.log(3);
}

run();
   function run() {
      one();
      two(); 
    }

    function one() {
      console.log(1);
    }

    function two() { 
      setTimeout(function() {
        console.log(2);
         three()
      })
    }

    function three() {
      console.log(3);
    }

    run();
Related