简体   繁体   English

使用从请求返回的“正文”

[英]Using 'body' returned from Request

I am using https://github.com/request/request .我正在使用https://github.com/request/request

The example that is given is:给出的例子是:

const request = require('request');

request('http://www.google.com', function (error, response, body) {
   console.error('error:', error); // Print the error if one occurred
   console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
   console.log('body:', body); // Print the HTML for the Google homepage.
});

How can I use body elsewhere in my code?如何在代码的其他地方使用body I want something like return body but nothing works.我想要return body之类的东西,但没有任何效果。 I can't use it anywhere!我不能在任何地方使用它!

You cannot directly return an asynchronous result from outside the request() callback.您不能直接从request()回调外部返回异步结果。 This is not unique to this particular function, but is how all asynchronous callbacks work in Javascript.这不是这个特定的 function 所独有的,而是所有异步回调在 Javascript 中的工作方式。

When you call request() it starts an asynchronous operation and turns it over to native code.当您调用request()时,它会启动一个异步操作并将其转换为本机代码。 The JS interpreter then goes about it's merry way executing the rest of your Javscript after this function call (not in the callback, but after that).然后,JS 解释器在此 function 调用之后(不在回调中,但在那之后)以愉快的方式执行 Javscript 的 rest。 So, you should be able to immediately see that the body result does not exist yet, but the rest of your Javascript is already executing.因此,您应该能够立即看到body结果还不存在,但是您的 Javascript 的 rest 已经在执行。

Then, some indeterminate time later (depending upon how responsive the server is that you're contacting and how big the result is), when the JS interpreter has nothing else to do, the callback gets called and the body result is available.然后,一段时间后(取决于您正在联系的服务器的响应速度以及结果的大小),当 JS 解释器无事可做时,回调被调用并且body结果可用。

So, the ONLY place in your code that you know the body result is good and is available is INSIDE that callback.因此,您知道body结果良好且可用的代码中唯一的位置是在该回调内部。 So, the general way of programming with an asynchronous operation like this in Javascript is that you use the result inside the callback.因此,在 Javascript 中使用这样的异步操作进行编程的一般方法是在回调中使用结果。 Any code that needs to use that result gets put inside that callback or you can put the code in a separate function and call that function from inside the callback and pass the body result as an argument to the function.任何需要使用该结果的代码都放在该回调中,或者您可以将代码放在单独的 function 中并从回调中调用 function 并将body结果作为参数传递给 ZC1C425268E68385D1AB507A49。

If you wanted to wrap this request in a function and communicate back that result to the caller (which is not exactly what you show here, but another way to write the code), I'd suggest you first read How do I return the response from an asynchronous call?如果您想将此请求包装在 function 中并将该结果传达给调用者(这与您在此处显示的内容不同,而是另一种编写代码的方式),我建议您先阅读如何返回响应来自异步调用? because it outlines the various ways you can communicate back the body result from your asynchronous operation (another callback or use promises).因为它概述了您可以通过异步操作(另一个回调或使用承诺)将body结果传达回的各种方式。


To many newbie Javascript developers this seems somewhat heretical.对于许多新手 Javascript 开发人员来说,这似乎有些异端。 What do you mean I can't just call a function, get the result and return it from the function?你是什么意思我不能只调用 function,得到结果并从 function 返回? Well, that's the extra complication with Javascripts non-blocking, asynchronous I/O model that is entirely event driven.嗯,这就是完全由事件驱动的 Javascript 非阻塞异步 I/O model 的额外复杂性。 Once you get down the learning curve, you will find a huge number of advantages in the language that flow from this architectural model, but you will have to deal with this extra complication.一旦你走下学习曲线,你会发现这种架构 model 所带来的语言的大量优势,但你将不得不处理这个额外的复杂性。

The language is evolving to make this type of programming simpler with the use of promises in async functions and then the use of await to "wait" on a promise.该语言正在不断发展,通过在async函数中使用 Promise,然后在 promise 上使用await来“等待”,从而使这种类型的编程变得更简单。 If you use the request-promise library instead of the request library (request-promise is derived from request), then you can deal with a promise as the return value and you have more options.如果你使用request-promise库而不是request库(request-promise 是从 request 派生的),那么你可以处理一个 promise 作为返回值,你有更多的选择。

const rp = require('request-promise');

async getMeSomeData() {
    try {
        let body = await rp('http://www.google.com');
        console.log(body);

        // can put code here that uses body

        return body;         // becomes the resolved value of the returned promise

    } catch(err) {
        console.log(err);
        throw err;           // makes sure the returned promise is rejected
    }   
});

getMeSomeData().then(body => {
    // use the body here
}).catch(err => {
    // error here
});

Note: I showed possibly using the body value or err inside getMeSomeData() or at the caller.注意:我展示了可能在getMeSomeData()或调用者处使用body值或err Usually, you would do one or the other, but I wanted to show both ways.通常,你会做其中一种,但我想展示两种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM