How to do repeated requests until one succeeds without blocking in node?

前端 未结 7 2018
执笔经年
执笔经年 2021-01-31 17:35

I have a function that takes a parameter and a callback. It\'s supposed to do a request to a remote API and get some info based on the parameter. When it gets the info, it needs

7条回答
  •  孤街浪徒
    2021-01-31 17:43

    Is this what you are trying to do?

    var history = {};
    
    function sendRequest(options, callback) {
        var req = https.request(options, function (res) {
            var acc = "";
            res.on("data", function (msg) {
                acc += msg.toString("utf-8");
            });
            res.on("end", function () {
                history = JSON.parse(acc);
                if (history.success) {
                    callback(history);
                }
                else {
                    sendRequest(options, callback);
                }
            });
        });
        req.end();
    }
    
    sendRequest(options, callback);
    

提交回复
热议问题