JavaScript Wait for function to Finish: 3 Ultimate Solutions

What is the proper way in JavaScript to wait for one function to finish before continuing?

By default, JavaScript carries out code execution asynchronously.

Here’s an example:

function first() {
  console.log("First function finished");
}

function second() {
  console.log("Second function finished");
}

function third() {
  console.log("Third function finished");
}

first();
second();
third();

JavaScript reads and runs your code from the start to the end, so the result will look like this:

Output:

First function finished
Second function finished
Third function finished

It simply means that it doesn’t pause for a function to complete before moving on to the code that follows it.

So that is why this article will show you various methods on how to wait for a function to finish in JavaScript.

How to wait for a function to finish in JavaScript?

When you’re working with JavaScript, you have the option to wait until a task is complete.

How you do this depends on what you’re trying to accomplish and how the task works, especially since it might not happen in order.

The following are some of the techniques you may use:

Wait for a function to finish using callback() functions with setTimeout() method 

One way to wait for one function to finish before continuing in JavaScript is to use a callback function.

A callback function is a function that is passed as an argument to another function and is executed after the first function has been completed.

Callback functions are often used in asynchronous programming to specify what should happen after an asynchronous operation has been completed.

Here’s an example code:

function firstFunction(callback) {
  console.log("First function finished");

  callback(); ✅
}

function secondFunction(callback) {
  console.log("Second function finished");

  callback(); 
}

function thirdFunction() {
  console.log("Third function finished");
}

setTimeout(function () {
  firstFunction(function () {
    secondFunction(function () {
      thirdFunction();
    });
  });
}, 0);

Here’s the explanation of the given example above, using callback functions and setTimeout in JavaScript:

  1. The firstFunction, secondFunction, and thirdFunction functions are defined. Each of these functions takes a callback function as an argument, logs a message to the console, and then calls the callback function.

  1. The setTimeout function is called with an anonymous function as its first argument and 0 as its second argument. This schedules the anonymous function to be executed after 0 milliseconds (i.e., as soon as possible).

  1. When the anonymous function passed to setTimeout is executed, it calls firstFunction and passes in another anonymous function as a callback.

  1. The firstFunction logs “First function finished” to the console and then calls the callback function.

  1. The callback function passed to firstFunction calls secondFunction and passes in yet another anonymous function as a callback.

  1. The secondFunction logs “Second function finished” to the console and then calls the callback function.

  1. The callback function passed to secondFunction calls thirdFunction.

  1. The thirdFunction logs “Third function finished” to the console.

The final output of the code will be:

First function finished
Second function finished
Third function finished

Wait for a function to finish using Promise object with then() method 

Another way to handle asynchronous behavior in JavaScript is to use Promise object with then() method.

A Promise object in JavaScript represents a value that may not be available yet but will be at some point in the future.

It is a way to handle asynchronous operations, such as making an API call or reading a file, without blocking the execution of your code.

Here’s an example:

function firstFunction() {
  return new Promise((resolve) => {
    console.log("First function finished");
    resolve();
  });
}

function secondFunction() {
  return new Promise((resolve) => {
    console.log("Second function finished");
    resolve();
  });
}

function thirdFunction() {
  console.log("Third function finished");
}

firstFunction().then(() => secondFunction().then(thirdFunction));

The example code above demonstrates how you can use Promise objects and the then method to manage the flow of asynchronous operations in JavaScript.

By chaining multiple calls to the then method, you can specify a sequence of operations that should be performed in order, with each operation only starting after the previous one has completed.

Here’s the explanation of the given example above, using a Promise object to wait for a function to finish in JavaScript:

  1. The firstFunction, secondFunction, and thirdFunction functions are defined. The firstFunction and secondFunction each return a new Promise object, while thirdFunction logs a message to the console.

  1. The firstFunction function is called, returning a Promise object.

  1. The then method is called on the Promise returned by firstFunction, with an anonymous function as its argument.

  1. When the Promise returned by firstFunction is resolved, the anonymous function passed to its then method is executed. This function calls secondFunction, which returns another Promise object.

  1. The then method is called on the Promise returned by secondFunction, with the thirdFunction function as its argument.

  1. When the Promise returned by secondFunction is resolved, the thirdFunction function is executed, logging “Third function finished” to the console.

So, the final output of the code will be:

First function finished
Second function finished
Third function finished

Use the async/await keywords to wait for a function to finish in JavaScript

The async and await keywords are used in JavaScript to make asynchronous programming easier.

An async function is a function that is declared with the async keyword and returns a Promise.

The await keyword can be used inside an async function to pause the execution of the function until a Promise is resolved.

Here’s an example of using the async/await keywords to wait for a function to finish in JavaScript:

async function firstFunction() {
    // simulate an asynchronous operation
    await new Promise(resolve => setTimeout(resolve, 1000));
    console.log('First function finished');
}

async function secondFunction() {
    console.log('Second function started');
    await firstFunction();
    console.log('Second function finished');
}

secondFunction();

  1. The firstFunction is an async function that uses the await keyword to wait for a Promise to be resolved.

  1. The Promise is created using the Promise constructor and is resolved after a delay of 1 second using the setTimeout function.

  1. When the Promise is resolved, the await expression completes and the next line of code is executed, logging ‘First function finished’ to the console.

  1. The secondFunction is also an async function that uses the await keyword to wait for firstFunction to complete. When secondFunction is called, it logs ‘Second function started’ to the console, then calls firstFunction and waits for it to complete using the await keyword.

  1. Once firstFunction has completed, the next line of code is executed, logging ‘Second function finished’ to the console.

The output of this code will be:

Second function started
First function finished
Second function finished

The async/await syntax provides a clean and readable way to write asynchronous code in JavaScript. It allows you to write code that looks like synchronous code, even though it is actually performing asynchronous operations.

Conclusion

In conclusion, this article delves into different approaches for managing asynchronous behavior in JavaScript, specifically focusing on how to wait for a function to finish.

We introduce callback functions with setTimeout(), Promise objects with then(), and the elegant async/await keywords.

These methods help programmers handle tasks that take time to finish in a smooth and organized way.

We are hoping that this article provides you with enough information that helps you understand the JavaScript wait for function to finish.  

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading itsourcecoders 😊.

Leave a Comment