简体   繁体   English

Node.js中的Https请求

[英]Https request in Node.js

I'm using the request library in Node.js to do a https request to get data from another service. 我正在使用Node.js中的请求库来执行https请求,以从另一个服务获取数据。 This is called asynchronously, right? 这被称为异步,对吗? So my code keeps running before all of the data is there, correct? 所以我的代码在所有数据都存在之前就一直运行,对吗?

My problem is that the data is needed right afterwards to calculate some things. 我的问题是,之后需要数据来计算一些东西。 My code throws an error during that calculation because the data from the service is undefined... Could it be possible that the data is just not there yet? 由于未定义来自服务的数据,因此我的代码在计算过程中引发了错误...可能数据还不存在吗? And if so, what do you do against that? 如果是这样,您将如何应对?

Here is a copy of the request: 这是请求的副本:

const request = require('request');

request(someUrl, {"Accept": "application/json"}, (err, res, body) => {
    if (err)
        handleError(err);
    body = JSON.parse(body);
    return body;
});

This kind of situation is pretty common in react/angular/vue kinda web apps, sometimes you need the data right away. 这种情况在React / Angular / Vue类Web应用程序中很常见,有时您需要立即获取数据。 But it is not available then, after a Rest call or something it becomes available. 但是在Rest呼叫或其他功能可用后,它不可用。

So, the simplest solution? 那么,最简​​单的解决方案?
Just add a check , for example: 只需添加一个检查 ,例如:

const calculate = (someVal)=>{
    if(!someVal) return ;
    //otherwise do the calculation
}

There are plenty of other ways, by mostly making the calculation async. 还有许多其他方法,主要是使计算异步。 For your function, you can do this 对于您的功能,您可以执行此操作

const promOp = function(){
    return new Promise((resolve, reject) => {
        request(someUrl, {"Accept": "application/json"}, (err, res, body) => {
            if (err) reject(err);
            body = JSON.parse(body);
            resolve(body);
        });
    }
}
//then
promOp()
.then((body)=>{
    //calculate here
})

//or can use the `Async/Await` syntax instead of then
const op = async () => {
    const body = await promOp;
    //calculate here
}

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

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