为什么等待对节点请求模块不起作用? [英] Why await is not working for node request module?

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

问题描述

我是nodejs的新手.我在示例1中没有看到回复,但是在示例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.

Ex 1

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

Ex 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?

推荐答案

对于返回Promise的内容,您只应await.我绝对建议您在开始使用asyncawait之前阅读Promises.您可能可以通过在request周围创建自己的包装函数以使其返回承诺来使该示例工作,例如:

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

或者,您可以使用 request-promise 来代替常规请求模块

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

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

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