我與Facebook的圖形API,這往往會返回一個「未知錯誤」的消息,我覺得如果我幾秒鐘後重試後它的工作原理沒有問題的工作。如何組織一個遞歸調用的承諾
此代碼將爲postAsync一個電話,在收到成功應答,將解決與新的承諾,否則會增加的嘗試計數器,並再次調用該函數。
function guaranteedPost(endpointId, wallPost, attempts){
attempts = attempts || 0
++attempts
return graph.postAsync(endpointId + '/feed', wallPost).then(function(response){
return new Promise.resolve(response)
}).catch(function(error){
setTimeout(function(){
console.log(attempts)
console.log(error)
if(attempts == 2){
return Promise.reject('Too many attempts')
}
else{
return guaranteedPost(endpointId, wallPost, attempts)
}
}, 5000)
});
}
guaranteedPost(endpointId, wallPost, 0).then(function(value){
console.log(value)
})
.catch(function(error){
console.log(error)
})
我希望能夠使用的代碼,例如,在那裏我稱之爲guaranteedPost,並登錄到控制檯或者響應,或單一的「嘗試次數過多」的錯誤消息。但是,在現階段,我收到我的輸出:
undefined
Unhandled rejection Error: Too many attempts
因此,不確定的第一個電話的回報和第二個電話,其中有沒有錯誤處理,炸燬。
另外,我想這可以訪問之前定義的變量更大的功能範圍內使用,因此,我不希望拔出錯誤和成功處理成自己的功能。
我不禁覺得我很接近,但是這是一個完整的重構或兩個後,我還是不太釘子它。我如何正確設計這個?
遞歸你必須從'guaranteedPost' – laggingreflex
對不起調用'guaranteedPost',我剛剛改名功能張貼在S.O.更新的代碼實際上反映了我正在使用的內容。 – Antoine