繁体   English   中英

Node.js中的Https请求

[英]Https request in Node.js

我正在使用Node.js中的请求库来执行https请求,以从另一个服务获取数据。 这被称为异步,对吗? 所以我的代码在所有数据都存在之前就一直运行,对吗?

我的问题是,之后需要数据来计算一些东西。 由于未定义来自服务的数据,因此我的代码在计算过程中引发了错误...可能数据还不存在吗? 如果是这样,您将如何应对?

这是请求的副本:

const request = require('request');

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

这种情况在React / Angular / Vue类Web应用程序中很常见,有时您需要立即获取数据。 但是在Rest呼叫或其他功能可用后,它不可用。

那么,最简​​单的解决方案?
只需添加一个检查 ,例如:

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

还有许多其他方法,主要是使计算异步。 对于您的功能,您可以执行此操作

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