Sometimes, we want to wait for a JavaScript Promise to resolve before resuming function.
In this article, we’ll look at how to wait for a JavaScript Promise to resolve before resuming function.
How to wait for a JavaScript Promise to resolve before resuming function?
To wait for a JavaScript Promise to resolve before resuming function, we use async
and await
.
For instance, we write
const wrapperFunc = async () => {
try {
let r1 = await someFunc();
let r2 = await someFunc2(r1);
return someValue;
} catch (e) {
console.log(e);
throw e;
}
};
to call someFunc
and someFunc2
which return promises.
We use await
to wait for the returned promises to finish in each function and then get their resolved value.
If any returned promise is rejected, then the catch
block runs and we get the rejected reason from the e
parameter.
We can only use await
inside async
functions and async
functions only return promises.
Conclusion
To wait for a JavaScript Promise to resolve before resuming function, we use async
and await
.