Created
August 16, 2016 03:34
-
-
Save tywong/e0e2f07756568ba48aae0f012ee5efb2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Promise = require('bluebird'); | |
var request = require("request-promise"); | |
//////////////////////////////////////////// | |
function requestWithRetry(param, maxRetry) { | |
//////// Inner function //////// | |
function retryBlock(iter, timeout) { | |
// console.log("waiting for timeout..."); | |
return new Promise( | |
(fulfill, reject) => { | |
setTimeout(() => { | |
return loop(iter+1, timeout * 2).then( | |
(data) => fulfill(data) | |
).catch( | |
(err) => reject(err) | |
) | |
}, | |
timeout * 1000) | |
} | |
) // new promise ends | |
} | |
//////// Inner function //////// | |
function loop(iter, timeout) { | |
// console.log("request", iter); | |
return request(param).catch( | |
(err) => { | |
if(iter >= maxRetry) | |
return Promise.reject(err); | |
else | |
return retryBlock(iter, timeout); | |
} | |
); | |
} | |
//////// Main stuff //////// | |
return loop(0, 2); // 2nd param, starting timeout value | |
} | |
//////////////////////////////////////////// | |
var url = "http://molamola.fake.com/"; | |
requestWithRetry({ "uri": url, "encoding": null, "timeout": 60 * 1000 }, 3).then( | |
(data) => { | |
console.log("success", data); | |
} | |
).catch( | |
(err) => { | |
console.log("failed:", err); | |
} | |
).finally( | |
() => { | |
console.log("end of chain"); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment