在承诺链中使用等待

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

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

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

callback没有被声明为async函数。 你只能直接在async函数中await一个Promise

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

此外,如果您正在利用asyncfunction, then 不需要使用它。

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