为什么我的超时重试得到不确定的结果

时间:2019-09-18 04:21:04

标签: javascript node.js

我尝试用超时实现重试,即使我在每个函数调用中都使用await,但从第2行返回的结果仍然不确定

我试图使用async.retry()包来处理重试,但是遇到了类似的问题。


let result = await retry(5, handleAPI, handleReponse, [200], URL, "GET");
console.log("result == " + result); // undefined


function handleReponse(body) {
    return body.id;
}


// handle retry
async function retry(retryCount, functionToRetry, callback, validStatusCode, ...args) {
    async function attempt() {
        if (retryCount != 0) {
          retryCount--;
          var response = await functionToRetry(...args);
          const { statusCode, body } = response;
          if (validStatusCode.includes(statusCode)) {
            const res = callback(body);
            console.log("res of callback is " + res); // it logged correct result here
            return res;
          } else {
                setTimeout(attempt(), 1000); // wait 1000ms to retry
          }

        }
        throw new Error('unsuccesfully.');
    }
    attempt();
}

// handle api
async function handleAPI(URL,  type){
    console.log('URL is', URL);
    const response = await httpClient(URL, {
        method: type,
        json: true,
    })
    .then(response => {
    const { statusCode, body } = response;
    console.log(' response statusCode: ', statusCode);
    // console.log('response body: ', body);
    return response;
    }).catch(err => {
        console.log(' Api call error: ', err);
    });

    return response;
}

1 个答案:

答案 0 :(得分:1)

您要从attempt()返回值,而不是从retry()返回值,为避免这种情况,请使用Promise。对于重复性任务,请使用setInterval,如下所示:

async function retry(retryCount, functionToRetry, callback, validStatusCode, ...args) {
return await new Promise((res, rej) => {
    var interval = setInterval(() => attempt(), 1000);
    function attempt() {
        if (retryCount != 0) {
            retryCount--;
            var response = await functionToRetry(...args);
            const { statusCode, body } = response;
            if (validStatusCode.includes(statusCode)) {
                const result = callback(body);
                console.log("res of callback is " + res); // it logged correct result here
                clearInterval(interval);
                res(result);
            }
        }
        clearInterval(interval);
        rej();
        throw new Error('unsuccesfully.');
    }
})   

}