Reputation: 6167
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?
Upvotes: 19
Views: 23457
Reputation: 13256
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;
};
Upvotes: 31