2016-02-03 40 views
3

我目前有工作代碼,執行請求,並檢查它是否收到一個成功的狀態代碼200.我想在此上成長,並循環它將繼續發送請求,直到狀態碼是200.我嘗試使用while循環但沒有收到正確的結果。謝謝您的幫助!節點JS:請求循環,直到狀態代碼200

request('http://0.0.0.0:9200', function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
     console.log('success'); 
     do(something); 
    } 
    else { 
     console.log('fail'); 
    } 
}); 
+0

可以將請求包裝在一個函數中,然後讓它在失敗情況下自行調用? – millerbr

回答

8

會是這樣的:

let retry = (function() { 
    let count = 0; 

    return function(max, timeout, next) { 
    request('http://0.0.0.0:9200', function (error, response, body) { 
     if (error || response.statusCode !== 200) { 
     console.log('fail'); 

     if (count++ < max) { 
      return setTimeout(function() { 
      retry(max, timeout, next); 
      }, timeout); 
     } else { 
      return next(new Error('max retries reached')); 
     } 
     } 

     console.log('success'); 
     next(null, body); 
    }); 
    } 
})(); 

retry(20, 1000, function(err, body) { 
    do(something); 
}); 

您可以設置重試的最大數量和重試之間的超時。這樣你就不會引入一個無限循環,並且你不會向重載的請求目標傳遞最後一拳^^

+0

你介意解釋這個功能是如何工作的。我已經實現了它,但理解仍然有點模糊。 – emarel

+0

你不明白什麼? – migg

1

我想要一個更直觀的答案,包括promise。我建立在miggs答案之內嘗試/捕捉下面的承諾和axios代碼。基於遞歸函數

const throwNumbers = (count = 0) => { 
    console.log(count); 
    if (count++ < 10) { 
    throwNumbers(count); 
    } else { 
    console.log('max reached'); 
    }; 
}; 

你可以把任何東西上試一試其他的部分,並在捕捉部分處理錯誤代碼一個簡單的例子

。你必須設置最大重試次數,在我的情況下是10次。

let getResponse = async(count = 0) => { 
    try { 
    const axiosResponse = await axios.get(someURL, { 
     params: { 
     parameter1: parameter1, 
     }, 
    }); 
    return axiosResponse; 
    } catch (error) { 
    if (error || error.status != 200) { 
     console.error('failed, retry'); 

     if (count++ < 10) { 
     return getResponse(count); 
     } else { 
     throw new Error('max retries reached'); 
     }; 
    } else { 
     throw error; 
    }; 
    }; 
}; 

你會調用該函數具有以下,並與響應值處理機構或什麼的。

let response = await getResponse(); 
console.log('This is the response:', response); 

沒有超時但爲我工作。