node.js - 为什么等待不适用于 Node 请求模块?

标签 node.js asynchronous async-await ecmascript-next

我是 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 调用中工作。但它不适用于请求调用。为什么?

最佳答案

你应该只对返回 Promise 的东西 await。在开始使用 asyncawait 之前,我绝对会推荐阅读 Promises。您可能可以通过围绕 request 创建自己的包装函数以使其返回 promise ,从而使该示例正常工作,如下所示:

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();

编辑:或者,您可以考虑使用 a promise-based request library而不是常规的请求模块。

关于node.js - 为什么等待不适用于 Node 请求模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38428027/

相关文章:

node.js - NodeJS 与 Einaros WebSocket : Client Ping Server VS Server Ping Client

node.js - 如何从 Firebase 向 node.js 发送通知?

javascript - 单元测试异步 Express 中间件

javascript - 将数据传递回异步请求的调用函数

node.js - 如何使用 ES7 语法从 Node.js VM 脚本检索异步结果

async-await - 我如何通过特征及其相关生命周期加入嵌套的 BoxFutures?

json - 部署 Aurelia/Node 应用程序时需要什么?

javascript - Node.js async.Detect 如果没有结果

javascript - 无法从异步函数检索返回的对象

javascript - 准确检查一个 bool 选项集