I just upgraded to node 8 and want to start working with async/await. I came across an error which took me a while to solve and I was actually just wondering if there's a more graceful way. I didn't want refactor the whole function at this point in time because of all the secondary refactors it would lead to.
async doSomething(stuff) {
...
return functionThatReturnsPromise()
.then((a) => ...)
.then((b) => ...)
.then((c) => {
const user = await someService.createUser(stuff, c);
user.finishSetup();
});
};
is there a way to be able to use await
in the promise chain without having to refactor everything above to be async
as well?
The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.
Promise chains can become difficult to understand sometimes. Using Async/Await makes it easier to read and understand the flow of the program as compared to promise chains.
The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result.
Approach: You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need to return the promise as an output from that asynchronous function.
The callback is not declared as an async
function. You can only await
a Promise
directly inside of an async
function.
async doSomething(stuff) {
// ...
return functionThatReturnsPromise()
.then((a) => /* ... */)
.then((b) => /* ... */)
.then(async (c) => {
const user = await someService.createUser(stuff, c);
return user;
});
};
Moreover, you shouldn't need to use then
if you are leveraging async
functions.
async doSomething(stuff) {
// ...
const a = await functionThatReturnsPromise();
const b = // ...
const c = // ...
const user = await someService.createUser(stuff, c);
return user;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With