在我的程序中,我使 async
从另一个 API 模块调用我的函数:
var info = await api.MyRequest(value);
模块代码:
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 result
and therefore info
contains request object and request body - info.body
like key=value&...
, not required response body.
我做错了什么?怎么修?什么是正确的 request
与 async
一起使用,或者它只适用于此处提到的承诺: 为什么等待不适用于节点请求模块?以下文章提到它是可能的: Mastering Async Await in Node.js 。
原文由 Aleksey Kontsevich 发布,翻译遵循 CC BY-SA 4.0 许可协议
您需要使用
request-promise
模块,而不是request
模块或http.request()
。await
适用于返回承诺的函数,而不适用于返回request
对象的函数,并希望您使用回调或事件侦听器来知道事情何时完成。The
request-promise
module supports the same features as therequest
module, but asynchronous functions in it return promises so you can use either.then()
orawait
使用它们而不是request
模块期望的回调。因此,安装
request-promise
模块,然后更改:对此:
然后,你可以这样做:
编辑 2020 年 1 月 - request() 模块处于维护模式
仅供参考,
request
模块及其衍生产品,如request-promise
现在处于维护模式,不会积极开发以添加新功能。您可以在 此处 阅读有关推理的更多信息。 此表 中有一个备选方案列表,并对每个备选方案进行了一些讨论。我自己一直在使用
got()
并且它从一开始就使用 Promise 构建,支持许多与request()
模块相同的选项,并且易于编程。