簡體   English   中英

如何等到 HTTP 請求完成才能完成 function

[英]How to wait until a HTTP request is complete to finish function

我最近開始學習 javascript,特別是 node.js,並且在我正在編寫的程序中遇到了問題。

基本上我需要發出一個 HTTP 請求,然后根據響應設置一個變量。

問題似乎是當我的 node.js 程序發送響應時變量為空。 這是 HTTP 請求的代碼:


function search(productCategory, productId) {

  var options = {
        "method": "GET",
        "hostname": 'HOSTNAME',
        "path": [
            "PATH",
        ],
        "headers": {
            "x-api-key": "API_KEY",

        }
    };


    var req =  http.request(options, function (res) {
        var chunks = [];

        res.on("data", function (chunk) {
            chunks.push(chunk);
        });

        res.on("end", function () {

            var body = Buffer.concat(chunks);


            var result = JSON.parse(body);

           var id = result.result[0].value;

            // console.log(id);
            return req.id;
        });
    });

     req.end();
}

console.log 正確輸出所需的值。

調用這個的 function 看起來像這樣:



module.exports = function getId(req, res) {

    var categoryId = "";
    var productId = '';
    var posId = "";

    for(var i=0; i < req.body.result[0].products.length; i++){

        categoryId = req.body.result[0].products[i].category_id;
        productId = req.body.result[0].products[i].product_id;
        posId = search(categoryId, productId);

        var product = {
            "product number": i,
            "product_category": categoryId,
            "product_id": productId,
            "posId": posId
        };

        productsArray.push(product);


    }

    res.send(JSON.stringify(orderingProducts));


};

目標是發送帶有從搜索方法獲得的鍵 posId 的對象數組的響應。

謝謝您的幫助!

好的,有多種方法可以做到這一點。 您可以為此使用 async/await 和 promise。 您可以在 web 上閱讀有關它們的信息 - 這很容易。 這是草稿示例:

function search(productCategory, productId) {
  // Here you return new promise
  return new Promise((resolve, reject) => {

  // Here you do your code and after it completes - resolve result
  var options = {
        "method": "GET",
        "hostname": 'HOSTNAME',
        "path": [
            "PATH",
        ],
        "headers": {
            "x-api-key": "API_KEY",

        }
    };


    var req =  http.request(options, function (res) {
        var chunks = [];

        res.on("data", function (chunk) {
            chunks.push(chunk);
        });

        res.on("end", function () {

            var body = Buffer.concat(chunks);
            var result = JSON.parse(body);
            var id = result.result[0].value;

            // console.log(id);
      
            //
            // Here you RESOLVE promise result
            resolve(id);
        });
    });

     req.end();

  });
}

在調用者 function 中,您將其修改為異步並在調用 promise function 之前添加等待

// Add async before function to handle await method
module.exports = async getId(req, res) {

    var categoryId = "";
    var productId = '';
    var posId = "";

    for(var i=0; i < req.body.result[0].products.length; i++){

        categoryId = req.body.result[0].products[i].category_id;
        productId = req.body.result[0].products[i].product_id;
        // Add await to PAUSE execution of this function and wait
        // the result from search promise
        posId = await search(categoryId, productId);

        var product = {
            "product number": i,
            "product_category": categoryId,
            "product_id": productId,
            "posId": posId
        };

        productsArray.push(product);


    }

    res.send(JSON.stringify(orderingProducts));


};

我認為您用於獲取 postId 的搜索 function 是異步的,如果這完全返回 promise,您需要通過 async/await 處理它。

唯一的改變,我在下面的代碼片段中制作了 function 異步並在搜索調用之前使用了等待,所以它等到我們得到 id。

module.exports = async function getId(req, res) {

var categoryId = "";
var productId = '';
var posId = "";

for(var i=0; i < req.body.result[0].products.length; i++){

    categoryId = req.body.result[0].products[i].category_id;
    productId = req.body.result[0].products[i].product_id;
    posId = await search(categoryId, productId);

    var product = {
        "product number": i,
        "product_category": categoryId,
        "product_id": productId,
        "posId": posId
    };

    productsArray.push(product);


}

res.send(JSON.stringify(orderingProducts));


};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM