在 Node.JS 中使用 async/await 正确请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45778474/
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
Proper request with async/await in Node.JS
提问by Aleksey Kontsevich
In my program I make asynccall for my function from another API module:
在我的程序中async,我从另一个 API 模块调用我的函数:
var info = await api.MyRequest(value);
Module code:
模块代码:
var request = require("request")
module.exports.MyRequest = async function MyRequest(value) {
var options = {
uri: "http://some_url",
method: "GET",
qs: { // Query string like ?key=value&...
key : value
},
json: true
}
try {
var result = await request(options);
return result;
} catch (err) {
console.error(err);
}
}
Execution returns immediately, however resultand therefore infocontains request object and request body - info.bodylike key=value&..., not required response body.
执行立即返回,但是result,并因此info包含请求对象和请求体-info.body样key=value&...,不需要响应体。
What I'm doing wrong? How to fix? What is proper requestusage with async, or it only works correctly with promises like mentioned here: Why await is not working for node request module? Following article mentioned it is possible: Mastering Async Await in Node.js.
我做错了什么?怎么修?什么是正确request使用async,或者它只适用于这里提到的承诺:Why await is not working for node request module?以下文章提到它是可能的:Mastering Async Await in Node.js。
回答by jfriend00
You need to use the request-promisemodule, not the requestmodule or http.request().
您需要使用request-promise模块,而不是request模块或http.request().
awaitworks on functions that return a promise, not on functions that return the requestobject and expect you to use callbacks or event listeners to know when things are done.
await适用于返回承诺的函数,而不适用于返回request对象并期望您使用回调或事件侦听器来知道事情何时完成的函数。
The request-promisemodule supports the same features as the requestmodule, but asynchronous functions in it return promises so you can use either .then()or awaitwith them rather than the callbacks that the requestmodule expects.
该request-promise模块支持与模块相同的功能request,但其中的异步函数返回承诺,因此您可以使用它们.then()或await与它们一起使用,而不是request模块期望的回调。
So, install the request-promisemoduleand then change this:
所以,安装request-promise模块,然后改变这个:
var request = require("request");
to this:
对此:
const request = require("request-promise");
Then, you can do:
然后,你可以这样做:
var result = await request(options);
EDIT Jan, 2020 - request() module in maintenance mode
编辑 2020 年 1 月 - request() 模块处于维护模式
FYI, the requestmodule and its derivatives like request-promiseare now in maintenance mode and will not be actively developed to add new features. You can read more about the reasoning here. There is a list of alternatives in this tablewith some discussion of each one.
仅供参考,该request模块及其衍生产品request-promise现在处于维护模式,不会积极开发以添加新功能。您可以在此处阅读有关推理的更多信息。此表中有一系列备选方案,并对每个备选方案进行了一些讨论。
I have been using got()myself and it's built from the beginning to use promises and is simple to use.
我一直在使用got()我自己,它从一开始就使用 Promise 构建,并且易于使用。
回答by user3520261
Pretty sure you can also do the following. If what you need does not return Promise by default you can provide it via new Promise method. Above answer is less verbose though.
很确定您也可以执行以下操作。如果您需要的默认情况下不返回 Promise 您可以通过新的 Promise 方法提供它。上面的答案虽然不那么冗长。
async function getBody(url) {
const options = {
url: url,
method: 'GET',
};
// Return new promise
return new Promise(function(resolve, reject) {
// Do async job
request.get(options, function(err, resp, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
})
})
}
回答by cbdeveloper
I just managed to get it to work with async/await. I wrapped it inside a function promisifiedRequestto return a promisethat runs the request callbackand resolves or rejects it based on errorand response.
我只是设法让它与async/await一起工作。我把它包在函数内部promisifiedRequest返回一个promise运行该请求callback并解析或它基于废品error和response。
const request = require('request');
const promisifiedRequest = function(options) {
return new Promise((resolve,reject) => {
request(options, (error, response, body) => {
if (response) {
return resolve(response);
}
if (error) {
return reject(error);
}
});
});
};
(async function() {
const options = {
url: 'https://www.google.com',
method: 'GET',
gzip: true,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36'
}
};
let response = await promisifiedRequest(options);
console.log(response.headers);
console.log(response.body);
})();

