node.js 为什么 await 不适用于节点请求模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38428027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:24:53  来源:igfitidea点击:

Why await is not working for node request module?

node.jsasynchronousasync-awaitecmascript-next

提问by user43286

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.

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

Ex 1

例 1

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

Ex 2

例 2

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

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?

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

回答by saadq

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

你应该只await在返回 Promise 的东西上。我绝对建议您在开始使用async和之前阅读 Promises await。您可以通过创建自己的包装器函数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() {
  let res = await doRequest(url);
  console.log(res);
}

main();

Edit: Alternatively, you can look into using a promise-based request libraryinstead of the regular request module.

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

回答by dimpiax

ES6

ES6

Usage:Where requestis require('./await-request')

用法:如果requestrequire('./await-request')

const init = async () => {
    try {
        const result = await request({
            uri: 'statdirectory/exchange?json',
            baseUrl: 'https://bank.gov.ua/NBUStatService/v1/',
            json: true
        })
        console.log(result)
    }
    catch (err) {
        console.error(err)
    }
}

Code:

代码:

// await-request.js
const request = require('request')

module.exports = async (value) => 
    new Promise((resolve, reject) => {
        request(value, (error, response, data) => {
            if(error) reject(error)
            else resolve(data)
        })
    })

回答by moztemur

As @saadq says you can only 'await' functions returning Promise.

正如@saadq 所说,您只能“等待”返回 Promise 的函数。

I like using Node.js's utilpackage to promisify a function with callback. So util+ requestcan be used like that:

我喜欢使用 Node.js 的util包来保证一个带有回调的函数。所以util+request可以这样使用:

const util = require('util')
const request = require("request");

const requestPromise = util.promisify(request);
const response = await requestPromise(url);
console.log('response', response.body);

Demo: https://runkit.com/mhmtztmr/node-js-request-with-async-await

演示:https: //runkit.com/mhmtztmr/node-js-request-with-async-await

回答by Piyush Bansal

Try with the following NPM package

尝试使用以下 NPM 包

node-fetch

节点获取

          var url = "http://www.google.com";
          try 
          {
            const response = await fetch(url);
            const json = await response.json();
            return {message:json.message,status:json.type};
          }
          catch(error)
          {
            console.log(error);
          }

Hope it works.

希望它有效。