Last active
January 6, 2020 07:58
-
-
Save vithalreddy/96ea7201b97346c61619aa2b28edaac9 to your computer and use it in GitHub Desktop.
Javascript settimeout in promise chain
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
// 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
Blog post link: https://stackfame.com/javascript-settimeout-promise-chain