Categories
JavaScript Answers

How to Reject a Promise with the JavaScript async/await Syntax?

Spread the love

The async and await syntax lets us write promise code that runs sequentially very cleanly.

It lets us do everything that we do with regular promise code.

Sometimes, we may want to reject a promise in the async function.

In this article, we’ll look at how to reject a promise with the JavaScript async and await syntax.

Throw an Error

One way to reject a promise in an async function is to throw an error inside it.

For instance, we can write:

const fn = async () => {  
  try {  
    await Promise.resolve(1)  
    await Promise.reject('error')  
  } catch (error) {  
    throw new Error(error);  
  }  
}  
fn()

We create the fn async function that has some promise code.

In the try block, we call Promise.reject to invoke a rejected promise.

Then we throw an error within the catch block, which will catch the rejected promise.

The error value is the string we pass into the Promise.reject method.

So we should see the 'error' string logged in the console since we threw the error in the catch block.

Throwing an Error instance lets us see the stack trace of the error and the content.

We can also throw anything with the throw keyword.

So we can write:

const fn = async () => {  
  try {  
    await Promise.resolve(1)  
    await Promise.reject('error')  
  } catch (error) {  
    throw error;  
  }  
}  
fn()

to just throw the error itself without putting it into the Error constructor.

But then now the console won’t show the stack trace.

It’ll only show the error value.

Return a Rejected Promise

We can also return a rejected promise in our code.

For instance, we can write:

const fn = async () => {  
  await Promise.resolve(1)  
  return Promise.reject('error')  
}  
fn()

to return a rejected promise.

Then when we run the function, we’ll only see the value we pass into the Promise.reject method and no stack trace.

We can do the same thing with any other rejected promise.

Conclusion

There’re various ways we can use to reject a promise with the async and await syntax.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *