An async
function rejects with whatever is thrown inside the function. Therefore, you simply need to throw
an error inside the async
function to make it reject. For example:
function wait(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function foo() { await wait(1000); throw new Error('Woops!'); } console.log(await foo()); // Uncaught Error: Woops!
As you can see in the example above, calling foo()
returns a Promise
that rejects with the Error
'Woops!'
.
As an alternative, you can also explicitly return a rejected Promise
using Promise.reject()
in the following way:
function wait(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function foo() { await wait(1000); return Promise.reject(new Error('Whoops!')); } console.log(await foo()); // Uncaught Error: Woops!
However, this approach is not idiomatic, and you should ideally, simply throw
an error to reject in an async
function.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.