Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using await in promise chain

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?

like image 486
jensengar Avatar asked Jul 30 '17 02:07

jensengar


People also ask

Can you use await on a promise?

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.

Why we use async await over simple promise chains?

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.

Does await wait for all promises?

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.

How do I convert async await to promises?

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.


1 Answers

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;
};
like image 184
thgaskell Avatar answered Sep 30 '22 18:09

thgaskell