Wait for a Promise to Resolve before Returning in JS

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
4 min

banner

# Table of Contents

  1. Wait for a Promise to Resolve before Returning in JavaScript
  2. Wait for N seconds before resolving a Promise
  3. Using a try/catch statement to handle Rejected promises
  4. Using then() to wait for a Promise to resolve before returning

# Wait for a Promise to Resolve before Returning in JavaScript

You can use the async/await syntax or call the .then() method on a promise to wait for it to resolve.

Inside functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

index.js
async function getNum() { const promise = new Promise(resolve => resolve(42)); const num = await promise; console.log(num); // ๐Ÿ‘‰๏ธ 42 return num; } getNum() .then(num => { console.log(num); // ๐Ÿ‘‰๏ธ 42 }) .catch(err => { console.log(err); });

wait for promise to resolve before returning

The code for this article is available on GitHub

We can use the await keyword to handle promises in functions marked as async.

The async/await syntax doesn't block the execution of all your JavaScript code. Rather, it runs the code in the function sequentially.

When the await keyword is used in a function, the next line of the function is not run before the promise has been resolved or rejected.

A Promise can have 3 states in JavaScript:

  1. pending - initial state, neither fulfilled nor rejected.
  2. fulfilled - the operation was successful and the promise is resolved.
  3. rejected - operation failed.

Even though the async function seemingly returns a number, it actually returns a promise.

All async functions wrap their return value in a Promise.

This is why we had to use the Promise.then() method to read the resolved value of the Promise.

# Wait for N seconds before resolving a Promise

You can use the setTimeout() function to wait for N seconds before resolving a Promise.

index.js
function getNum() { const resolveValue = 42; return new Promise((resolve, reject) => { setTimeout(() => { resolve(resolveValue); }, 3000); }); } getNum() .then(num => { console.log(num); // ๐Ÿ‘‰๏ธ 42 }) .catch(err => { console.log(err); });

wait for n seconds before resolving promise

The code for this article is available on GitHub

The function returns a new Promise that resolves with the value 42 after 3 seconds.

Notice that the function is not marked as async but it still returns a Promise.

The same approach can be used outside a function.

index.js
const p1 = new Promise(resolve => { const resolveValue = 42; setTimeout(() => { resolve(resolveValue); }, 3000); }); p1.then(num => { console.log(num); // ๐Ÿ‘‰๏ธ 42 }).catch(err => { console.log(err); });

The promise in the example resolves after 3 seconds with the value 42.

# Using a try/catch statement to handle Rejected promises

You can use a try/catch statement to handle a scenario where the promise is rejected.

index.js
async function getNum() { try { const promise = new Promise((resolve, reject) => reject(new Error('test error')), ); await promise; return "This doesn't run" } catch (err) { // ๐Ÿ‘‡๏ธ this runs throw err; } } getNum() .then(num => { console.log(num); }) .catch(err => { // ๐Ÿ‘‡๏ธ this runs console.log(err.message); // โ›”๏ธ "test error" });

using try catch statement to handle rejected promises

The code for this article is available on GitHub

If an error or a promise rejection occurs in the try block, the error gets passed to the catch block where we can handle it.

Alternatively, you could use the Promise.catch() method to catch an error as shown in the code sample above.

Calling the Promise.catch() method is the same as chaining another .then() call and passing a function as the second argument to the method.

index.js
async function getNum() { try { const promise = new Promise((resolve, reject) => reject(new Error('test error')), ); await promise; return "This doesn't run"; } catch (err) { // ๐Ÿ‘‡๏ธ this runs throw err; } } getNum() .then(num => { console.log(num); return num; }) .then(undefined, err => { console.log(err.message); // ๐Ÿ‘‰๏ธ "test error" });

It's good to know that the second parameter of the .then() method is a function that is called if the Promise is rejected.

However, this syntax is very rarely used.

# Using then() to wait for a Promise to resolve before returning

You could achieve the same result by using the Promise.then() method instead of async/await.

However, the Promise.then() syntax is a bit more verbose and harder to read.

index.js
function getNum() { const p1 = new Promise(resolve => { resolve(42); }); return p1.then(value => { // ๐Ÿ‘‡๏ธ can run code here before returning console.log(value); // ๐Ÿ‘‡๏ธ return from the function here return 'example function return value'; }); } getNum() .then(value => { console.log(value); // ๐Ÿ‘‰๏ธ example function return value return value; }) .catch(err => { console.log(err); });

using then to wait for promise to resolve before returning

The code for this article is available on GitHub

A very important detail in the code sample is that we return the call to promise.then() from the function.

If you don't return the promise.then() call, you will get an error as the function wouldn't return a Promise.

All functions that were marked as async return a Promise, however, in other functions, you have to explicitly return the Promise.

You can wait for the promise to resolve inside the .then() call.

The return value of the .then() method is always wrapped in a promise, so you can chain multiple calls to the .then() method.

index.js
const p1 = Promise.resolve(42); p1.then(value => { console.log(value); // ๐Ÿ‘‰๏ธ 42 return value + 1; }).then(value => { console.log(value); // ๐Ÿ‘‰๏ธ 43 return value + 2; });

The value you return from the .then() method gets wrapped in a promise and passed as a parameter in the next call to the .then() method.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev