在promise链中使用await

jen*_*gar 14 javascript node.js async-await

我刚刚升级到节点8,并希望开始使用async/await.我遇到了一个错误,我花了一些时间来解决这个错误,实际上我只是想知道是否有更优雅的方式.我不希望在这个时间点重构整个函数,因为它会导致所有的二级重构.

async doSomething(stuff) {
...

  return functionThatReturnsPromise()
    .then((a) => ...)
    .then((b) => ...)
    .then((c) => {
      const user = await someService.createUser(stuff, c);
      user.finishSetup();
    });
};
Run Code Online (Sandbox Code Playgroud)

有没有办法能够await在承诺链中使用而不必重构以上所有内容async

thg*_*ell 14

回调未声明为async函数.你只能await一个Promise直接内的的async功能.

async doSomething(stuff) {
// ...

  return functionThatReturnsPromise()
    .then((a) => /* ... */)
    .then((b) => /* ... */)
    .then(async (c) => {
      const user = await someService.createUser(stuff, c);
      return user;
    });
};
Run Code Online (Sandbox Code Playgroud)

此外,如果您正在利用功能,则不需要使用.thenasync

async doSomething(stuff) {
// ...

  const a = await functionThatReturnsPromise();
  const b = // ...
  const c = // ...
  const user = await someService.createUser(stuff, c);
  return user;
};
Run Code Online (Sandbox Code Playgroud)