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

前端 未结 7 2036
执笔经年
执笔经年 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条回答
  •  猫巷女王i
    2021-01-31 17:59

    Definitely not the way to go - while(!done); will go into a hard loop and take up all of your cpu.

    Instead you could do something like this (untested and you may want to implement a back-off of some sort):

    function tryUntilSuccess(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() {
                var history = JSON.parse(acc);  //<== Protect this if you may not get JSON back
                if (history.success) {
                    callback(null, history);
                } else {
                    tryUntilSuccess(options, callback);
                }
            });
        });
        req.end();
    
        req.on('error', function(e) {
            // Decide what to do here
            // if error is recoverable
            //     tryUntilSuccess(options, callback);
            // else
            //     callback(e);
        });
    }
    
    // Use the standard callback pattern of err in first param, success in second
    tryUntilSuccess(options, function(err, resp) {
        // Your code here...
    });
    

提交回复
热议问题