为什么 await 不适用于节点请求模块? [英] Why await is not working for node request module?

查看:29
本文介绍了为什么 await 不适用于节点请求模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to nodejs. I’m not seeing the response in ex 1, but i see in ex 2. Why? Await works for me in other places, using 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 调用中起作用.但它不适用于请求调用.为什么?

Await works in other places, I’m using babel and required modules for es6 and es7 features. For example, await works in squelize call, i validated. But it doesn’t work for request call. Why?

推荐答案

你应该只await 返回一个 Promise 的东西.我绝对建议您在开始使用 asyncawait 之前阅读 Promises.你可以通过围绕 request 创建你自己的包装函数来让它返回一个 promise,像这样:

You should only await on something that returns a Promise. I would definitely recommend reading up on Promises before you start working with async and await. You can probably get this example to work by creating your own wrapper function around request to make it return a promise, like so:

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() {
  let res = await doRequest(url);
  console.log(res);
}

main();

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

Alternatively, you can look into using a promise-based request library instead of the regular request module.

这篇关于为什么 await 不适用于节点请求模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆