Introduction
In today's fast-paced world, we often find ourselves needing to get information from an asynchronous function before moving on with our code. Whether it's data from a database or a response from an API, we need to know how to wait for the async function to finish before continuing.
Luckily, JavaScript provides us with a few ways to do this. In this article, we'll take a look at how to use Promises and async/await to wait for async function to finish. We'll also look at how to use setTimeout() to delay our code until the async function has been completed.
Understanding Promises in JavaScript
Promises are a way to handle asynchronous code in JavaScript. A promise represents a value that may not be available yet but will be resolved at some point in the future.
We can create a promise by using the Promise()
constructor:
const myPromise = new Promise((resolve, reject) => {
// do something async
resolve(); // fulfilled
reject(); // rejected
});
The Promise()
constructor takes a callback function with two parameters: resolve and reject. The resolve function is called when the async operation is successful, and the reject function is called when the async operation fails.
We can use Promises to wait for async function to finish by chaining a .then()
method to the end of our promise:
myPromise
.then(() => {
// do something when the promise is fulfilled
})
.catch(() => {
// do something when the promise is rejected
});
The .then()
method is called when the promise is resolved, and the .catch() method is called when the promise is rejected.
If we want to wait for multiple promises to finish, we can use Promise.all()
:
Promise.all([promise1, promise2, promise])
.then(() => {
// all promises have been resolved
})
.catch(() => {
// one or more promises have been rejected
});
However, we can define an asynchronous function using a specialized syntax. async/await
is a syntax that makes working with asynchronous code in JavaScript easier. It allows us to write asynchronous code that looks like synchronous code.
Use async/await
to wait for async function to finish
To use async/await, we need to declare a function as async:
async function myAsyncFunction() {
// do something async
}
Once we have an async function, we can use the await keyword inside of it. The await keyword can be used inside of an async function to pause the execution of the async function and wait for a promise to be resolved. It can only be used inside of an async function.
Here is an example:
async function myAsyncFunction() {
const result = await myPromise();
console.log(result);
}
In the example above, the execution of the myAsyncFunction
function will be paused until the myPromise
promise is resolved. Once the promise is resolved, the value returned by the promise will be assigned to the result variable and the console.log statement will be executed.
If the promise is rejected, then the await keyword will throw an error.
To show and illustrate how to wait for async function to finish by fetching the GitHub API, but since we have not set up API credentials, we should trigger the catch()
method.
async function fetchAsync() {
// await response of fetch call
let response = await fetch("<https://api.github.com>");
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
return data;
}
// trigger async function
fetchAsync()
// log response or catch error of fetch promise
.then((data) => console.log(data))
.catch((reason) => console.log("Message:" + reason.message));
Output
Message:fetch is not defined
Summary
To wait for async function to finish, we can make use of the await
keyword, and with the code example, we can understand how async/await
works.
References
async function - JavaScript | MDN (mozilla.org)
javascript - Wait for async task to finish - Stack Overflow
Proper way to wait for one function to finish before continuing?
Very nice little tutorial!
A link to a working demo on f.i. CodePen would make it one of the best.