async/await
async:The word async before a function means one simple thing: a function always returns a promise.
await:The keyword await makes JavaScript wait until that promise settles and returns its result.
Here
async function test() {
let task = asyncTask() //return a promise
//function still running
await task
//code executed only if task is resolved
}
The function execution “pauses” at the line (await task) and resumes when the promise settles, with task becoming its result.
Let’s emphasize: await literally makes JavaScript wait until the promise settles, and then go on with the result.
If a promise resolves normally, then await promise returns the result. But in case of a rejection it throws the error .
1. Either as already said in answer We should catch that error using try..catch
async function test() {
let task = asyncTask()
//function still running
try {
await task
} catch (err){
throw new Error(err);
}
}
2. If we don’t have try..catch, then the promise generated by the call of the async function test() becomes rejected. We can append .catch to handle it:
async function test() {
let task = asyncTask() //return a promise
//function still running
await task
//code executed only if task is resolved
}
test().catch(//error);
More If .catch is not there, then we get an unhandled promise error. We can catch such errors using a global event handler.