简体   繁体   English

如何从request.get获取正文中的信息到全局独家新闻

[英]how to get the information in body into the global scoop from request.get

Im totally new to JavaScript and I have a problem. 我对JavaScript完全陌生,我遇到了问题。

This is my code and it is working 这是我的代码,它正在工作

'use strict';

const request = require("request")
const url = "https://something/v1/"

request.get(
  `${url}/tickers?symbols=tBTCUSD`,
    (error, response, body) => console.log(body)
    )

So this writes the expected data on the screen. 因此,这会将期望的数据写入屏幕。 So I have the data, I just dont want to put it on my screen, I want to process it. 所以我有数据,我只是不想将其放在屏幕上,我想对其进行处理。 But how do I get that data out from the request.get function? 但是,如何从request.get函数获取数据呢?

Something like this 像这样

'use strict';

const request = require("request")
const url = "https://something/v1/"

let global_answer

request.get(
  `${url}/tickers?symbols=tBTCUSD`,
    (error, response, body) => {
        console.log(body)
        global_answer = body;
})

my_function(global_answer);

Declare a variable in the global scope like this: 在全局范围内声明一个变量,如下所示:

var debugBody;

request.get(
    `${url}/tickers?symbols=tBTCUSD`,
    (error, response, body) => {
        debugBody = body;
        console.log(body)
});

console.log(debugBody);

EDIT: Async function 编辑:异步功能

This won't work because request.get works asynchronously, if you want to call a function, you should have the function defined globally and call it from inside the request.get callback: 这是行不通的,因为request.get是异步工作的,如果要调用一个函数,则应该全局定义该函数,然后从request.get回调内部进行调用:

var debugBody;

function logRequestBody(body){
    console.log(body);
}

request.get(
    `${url}/tickers?symbols=tBTCUSD`,
    (error, response, body) => {
        logRequestBody(body);
});

The code will work that way. 该代码将以这种方式工作。

something more like this: 像这样:

'use strict';

const request = require("request");
const url = "${url}/tickers?symbols=tBTCUSD";

request.get(url, (error, response, body) => {
  console.log(body);
  my_function(body);
});

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

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