在for循环中使用async/await

Val*_*lip 3 javascript node.js async-await

如何在for循环中使用async/await?

这是我的代码:

export default (req, callback) => {
  // ...
  compliance.forEach((rule, index) => {
    let response = await waRuleOverview(req, run.id, rule.id);
    // handle the response
  });
}
Run Code Online (Sandbox Code Playgroud)

这是我定义waRuleOverview函数的方式:

export function waRuleOverview(req, runId, ruleId) {
  var def = deferred();

  setTimeout(function() {
    const apiToken = req.currentUser.apiToken;
    const payload = {
      'Authorization': 'api_key ' + apiToken
    }

    const options = {
      'method': 'get',
      'gzip': true,
      'headers': payload,
      'content-type': 'application/json',
      'json': true,
      'url': 'api-url'
    }

    request(options, (error, response, body) => {
      def.resolve(body);
    });
  }, 50);

  return def.promise;
}
Run Code Online (Sandbox Code Playgroud)

它会在控制台中抛出此错误:

等待是一个保留字

这个问题关系到其中一个我试图找出如何解决它.

Yur*_*nko 12

这取决于您希望如何执行异步代码:顺序执行或并行执行.无论如何,您需要添加async要使用的关键字await.

// sequential
export default async (req, callback) => {
  // ...
  for(const [rule, index] of compliance.entries()) {
    const response = await waRuleOverview(req, run.id, rule.id)

    // handle the response
  }
}

// parallel
export default async (req, callback) => {
  // ...
  const responses = await Promise.all(compliance
     .map((rule, index) => waRuleOverview(req, run.id, rule.id))
  )

  // handle responses
  responses.forEach(response => {
    // ...
    // handle response here
  })
}
Run Code Online (Sandbox Code Playgroud)

最后,如果你真的不希望你的处理程序返回一个Promise但只是希望它为副作用执行一些异步操作.

export default (req, callback) => {
  // ...
  compliance.forEach(/* add */ async (rule, index) => {
    // to use await inside
    let response = await waRuleOverview(req, run.id, rule.id);
    // handle the response
  });
}
Run Code Online (Sandbox Code Playgroud)

但这种方法实际上是一种反模式,因为它打破了承诺链:对可组合性,错误处理等不利.