An efficient way to execute two functions one after the other in Javascript

I have two functions

function one() {
    setTimeout(function(){ console.log("first function executed"); }, 3000);
}

function two() {
    console.log("second function executed");
}

      

How can I let the second function wait until the first function is executed? What's the easiest way for a beginner? Thanx

+3


source to share


1 answer


There are several ways in which you could approach this, the two most common are callbacks or using Promises.

Using callbacks

You would add a callback argument to the first function and then pass function 2 as a callback:

function one(callback) {
  setTimeout(function() {
    console.log("first function executed");
    callback();
  }, 3000);
}

function two() {
  console.log("second function executed");
}

one(two)
      

Run codeHide result




Using Promises:

Promises allow you to bundle different actions together, which are order-dependent. However, you may need to add policies to support older browsers:

function one(callback) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      console.log("first function executed");
      resolve();
    }, 3000);
  })
}

function two() {
  console.log("second function executed");
}

one().then(two)
      

Run codeHide result


+9


source







All Articles