为什么等待不适用于节点请求模块?

新手上路,请多包涵

我是nodejs的新手。我在 ex 1 中没有看到响应,但我在 ex 2 中看到了。为什么? Await 在其他地方为我工作,使用 babel。

例 1

  let res = await request(url)
 console.log(res);
 console.log(res.body);

前 2

 request(url, function (error, res, body) {
 if (!error && response.statusCode == 200) {
 console.log(body)
 }
});

Await 在其他地方工作,我正在使用 babel 和 es6 和 es7 功能所需的模块。例如,我验证了 await 在 squelize 调用中工作。但它不适用于请求调用。为什么?

原文由 user43286 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 245
1 个回答

你应该只 await 在返回承诺的东西上。我绝对建议您在开始使用 asyncawait 之前阅读 Promises。您可能可以通过围绕 request 创建自己的包装函数来使这个示例工作,使其返回一个承诺,如下所示:

 function doRequest(url) {
  return new Promise(function (resolve, reject) {
    request(url, function (error, res, body) {
      if (!error && res.statusCode === 200) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
}

// Usage:
async function main() {
  try {
    let response = await doRequest(url);
    console.log(response); // `response` will be whatever you passed to `resolve()` at the top
  } catch (error) {
    console.error(error); // `error` will be whatever you passed to `reject()` at the top
  }
}

main();

编辑:或者,您可以考虑使用 基于承诺的请求库 而不是常规请求模块。

原文由 Saad 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题