我刚刚升级到节点8,并希望开始使用异步/等待。我遇到了一个错误,这使我花了一段时间才能解决,实际上我只是想知道是否还有更优雅的方法。我不想在这个时候重构整个函数,因为它会导致所有二次重构。

async doSomething(stuff) {
...

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

有没有一种方法可以在promise链中使用await而不必将上面的所有内容都重构为async

最佳答案

回调未声明为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;
    });
};

此外,如果要利用then函数,则无需使用async
async doSomething(stuff) {
// ...

  const a = await functionThatReturnsPromise();
  const b = // ...
  const c = // ...
  const user = await someService.createUser(stuff, c);
  return user;
};

07-24 17:43
查看更多