Javascript settimeout in promise chain
// example code for blog post | |
// https://stackfame.com/javascript-settimeout-promise-chain | |
makeHttpCall("https://api.stackfame.com/1") | |
.then(function(data) { | |
return makeHttpCall("https://api.stackfame.com/2"); | |
}) | |
.then(function(data) { | |
return loadScript("https://api.stackfame.com/3"); | |
}) | |
.then(function(data) { | |
// do something useful with data | |
}); | |
makeHttpCall("https://api.stackfame.com/1") | |
// add delay here | |
.then(function(data) { | |
return makeHttpCall("https://api.stackfame.com/2"); | |
}) | |
// add delay here | |
.then(function(data) { | |
return loadScript("https://api.stackfame.com/3"); | |
}) | |
.then(function(data) { | |
// do something useful with data | |
}); | |
const delay = time => new Promise(resolve => setTimeout(resolve, time)); | |
makeHttpCall("https://api.stackfame.com/1") | |
// add delay here | |
.then(delay(10000)) | |
.then(function(data) { | |
return makeHttpCall("https://api.stackfame.com/2"); | |
}) | |
// add delay here | |
.then(delay(5000)) | |
.then(function(data) { | |
return loadScript("https://api.stackfame.com/3"); | |
}) | |
.then(function(data) { | |
// do something useful with data | |
}); | |
const delay = time => new Promise(resolve => setTimeout(resolve, time)); | |
// using es6 arrow functions | |
makeHttpCall("https://api.stackfame.com/1") | |
// add delay here | |
.then(delay(4000)) | |
.then(data => makeHttpCall("https://api.stackfame.com/2")) | |
// add delay here | |
.then(delay(2000)) | |
.then(data => loadScript("https://api.stackfame.com/3")) | |
.then( | |
data => console.log(data) | |
//do something useful with data | |
); | |
Promise.prototype.delay = time => | |
new Promise(resolve => setTimeout(resolve, time)); | |
makeHttpCall("https://api.stackfame.com/1") | |
// add delay here | |
.delay(4000) | |
.then(data => makeHttpCall("https://api.stackfame.com/2")) | |
// add delay here | |
.delay(5000) | |
.then(data => loadScript("https://api.stackfame.com/3")) | |
.then( | |
data => console.log(data) | |
//do something useful with data | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Blog post link: https://stackfame.com/javascript-settimeout-promise-chain