如何重复请求,直到一个成功而没有在节点中阻塞? [英] How to do repeated requests until one succeeds without blocking in node?

查看:37
本文介绍了如何重复请求,直到一个成功而没有在节点中阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带参数和回调的函数。它应该向远程API发出请求并根据参数获取一些信息。当它获得信息时,它需要将其发送到回调。现在,远程API有时无法提供。我需要我的功能继续尝试直到它设法完成它并且然后用正确的数据调用回调。

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 to send it to the callback. Now, the remote API sometimes fails to provide. I need my function to keep trying until it manages to do it and then call the callback with the correct data.

目前,我有下面的函数里面的代码,但我觉得像while(!done );是不正确的节点代码。

Currently, I have the below code inside the function but I think that stuff like while (!done); isn't proper node code.

var history = {};
while (true) {
    var done = false;
    var retry = true;
    var req = https.request(options, function(res) {
        var acc = "";
        res.on("data", function(msg) {
            acc += msg.toString("utf-8");
        });
        res.on("end", function() {
            done = true;
            history = JSON.parse(acc);
            if (history.success) {
                retry = false;
            }
        });
    });
    req.end();
    while (!done);
    if (!retry) break;
}
callback(history);

我该如何正确地做到这一点?

How do I do it the right way?

推荐答案

绝对不是要走的路 - 而(!完成);一些硬循环并占用你所有的cpu。

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

相反你可以做这样的事情(未经测试,你可能想要实现一些补偿sort):

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...
});

这篇关于如何重复请求,直到一个成功而没有在节点中阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆