在Node.JS中使用异步/等待正确的请求 [英] Proper request with async/await in Node.JS

查看:78
本文介绍了在Node.JS中使用异步/等待正确的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我从另一个API模块中调用async来调用我的函数:

In my program I make async call for my function from another API module:

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

执行立即返回,但是result因此info包含请求对象和请求正文-info.bodykey=value&...一样,不是必需的响应正文.

Execution returns immediately, however result and therefore info contains request object and request body - info.body like key=value&..., not required response body.

我做错了什么?怎么修? requestasync的正确用法是什么,或者只能与此处提到的承诺一起正常使用:为什么await在节点上不起作用请求模块?以下文章提到了可能:在Node.js中掌握异步等待

What I'm doing wrong? How to fix? What is proper request usage 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-promise模块,而不是request模块或http.request().

You need to use the request-promise module, not the request module or http.request().

await在返回promise的函数上起作用,而不在返回request对象并希望您使用回调或事件侦听器知道何时完成的函数上起作用.

await works on functions that return a promise, not on functions that return the request object and expect you to use callbacks or event listeners to know when things are done.

request-promise模块支持与request模块相同的功能,但是其中的异步函数返回Promise,因此您可以将.then()await与它们一起使用,而不是request模块的回调期望.

The request-promise module supports the same features as the request module, but asynchronous functions in it return promises so you can use either .then() or await with them rather than the callbacks that the request module expects.

因此,请安装 request-promise模块,然后进行以下更改:

So, install the request-promise module and then change this:

var request = require("request");

对此:

const request = require("request-promise");

然后,您可以执行以下操作:

Then, you can do:

var result = await request(options);


编辑2020年1月-维护模式下的request()模块

FYI,request模块及其派生类(例如request-promise)现在处于维护模式,不会积极开发以添加新功能.您可以在此处了解更多有关推理的信息. 此表中列出了一些替代方案,并对以下内容进行了讨论每一个.

FYI, the request module and its derivatives like request-promise are 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 table with some discussion of each one.

我一直在自己使用 got() ,它是从一开始就使用诺言和简单易用.

I have been using got() myself and it's built from the beginning to use promises and is simple to use.

这篇关于在Node.JS中使用异步/等待正确的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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