Skip to content

Instantly share code, notes, and snippets.

@vithalreddy
Last active January 6, 2020 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vithalreddy/96ea7201b97346c61619aa2b28edaac9 to your computer and use it in GitHub Desktop.
Save vithalreddy/96ea7201b97346c61619aa2b28edaac9 to your computer and use it in GitHub Desktop.
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
);
@vithalreddy
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment