循环调用api,直到响应成功

时间:2019-02-04 11:36:21

标签: javascript node.js express axios

我正在尝试从我的nodejs脚本进行rest API调用。我希望脚本继续对此API进行重复调用,直到获得肯定的结果为止。 这是我想要做的,但是我的脚本只是冻结了:

var success=0;

while(!success){

  axios.post('http://localhost:2000/evaluate', {serviceName:"s1"})
       .then((response)=>{
          if(response.data==1){
            success=1; //desired response, quit the loop
            res.send('1')
          }
          else{ //not the desired response, keep trying
            res.send('0') 
          }

}//end while loop

基本上,如何重复进行API调用,直到获得所需的响应?

谢谢!

2 个答案:

答案 0 :(得分:3)

用重试计数器替换success,并在必要时从回调中再次调用该函数。另外,请保持计数器状态,以防万一发生任何问题。

// your callback gets executed automatically once the data is received
var callback = (data, error) => {
    // consume data
    if (error) {
        console.error(error);
        return;
    }
    console.log(data);
};

// run the request. this function will call itself max. 5 times if the request fails
request(5, callback);

function request(var retries, var callback) {
    axios.post('http://localhost:2000/evaluate', {
        serviceName:"s1"
    }).then(response => {
        if(response.data == 1) {
            // request successful, deliver to script for consume
            callback(response);
        }
        else {
            // request failed
            // retry, if any retries left
            if (retries > 0) {
                request(--retries, callback);
            }
            else {
                // no retries left, calling callback with error
                callback([], "out of retries");
            }
        }
    }).catch(error => {
        // ajax error occurred
        // would be better to not retry on 404, 500 and other unrecoverable HTTP errors
        // retry, if any retries left
        if (retries > 0) {
            request(--retries, callback);
        }
        else {
            // no retries left, calling callback with error
            callback([], error);
        }
    });
}

答案 1 :(得分:-1)

您正在混淆代码的异步和同步性质,因为(我期望)axios.post(...)是一个异步函数,在while循环中被调用,其调用次数为100或1000倍一秒钟,导致您的代码冻结,

解决方案-递归函数 (请参阅朱利安的答案-https://stackoverflow.com/a/54515365/6743697

(我要输入,但他已经输入了。)