簡體   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