使用等待而不是Promises的正确方法是什么?

FXu*_*Xux 3 javascript asynchronous node.js promise async-await

我已经使用Promise很长一段时间了,它们总是我用来控制程序工作流程的"东西".例:

Promise
  .resolve(obj)
  .then(doSomething1)
  .then(doSomething2)
  .catch(handleError)
Run Code Online (Sandbox Code Playgroud)

而现在,我想改为试用风格,但我不知道究竟什么是正确的方法.

V1:

try {
  var body = await Promise
               .resolve(obj)
               .then(doSomething1)
               .then(doSomething2)
} catch (error) {
  callback(error)
}
callback(null, {
  statusCode: 200,
  body
})
Run Code Online (Sandbox Code Playgroud)

V2:

try {
  var body = await Promise
               .resolve(obj)
               .then(doSomething1)
               .then(doSomething2)
               .then(body => {
                 callback(null, {
                   statusCode: 200,
                   body
                 })
               })
} catch (error) {
  callback(error)
}
Run Code Online (Sandbox Code Playgroud)

什么是正确的方法?

Jac*_*cob 5

您不必使用回调函数来切换到async/ await.的async功能仅仅是一个承诺,返回功能,并且await是有作为的方便.所以相当于你原来的功能就是:

async function fn() {
  try { 
    const obj = ...;
    const result1 = await doSomething1(obj);
    const result2 = await doSomething2(result1);
    return result2;
  } catch (err) {
    return handleError(err);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果你确实想要那个回调:

async function fn(callback) {
  try { 
    const obj = ...;
    const result1 = await doSomething1(obj);
    const result2 = await doSomething2(result1);
    callback(null, result2);
  } catch (err) {
    callback(err);
  }
}
Run Code Online (Sandbox Code Playgroud)