Wait for a Promise to Resolve before Returning in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Wait for a Promise to Resolve before Returning #

You can use the async/await syntax or call the .then() method on a promise to wait for it to resolve. Inside of 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); });

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 ran before the promise has been resolved or rejected.

Even though our 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 return value of the function.

You could achieve the same result by using the Promise.then() method instead of async/await, but the Promise.then() syntax is a bit more verbose and harder to read.

You can use a try/catch block 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" });

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.

Calling the Promise.catch() method is the same as chaining another .then() call and passing a function as the second parameter 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 to the .then() method is a function that is called if the Promise is rejected. However, this syntax is very rarely used.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.