Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created December 16, 2017 02:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save primaryobjects/e6e9f7c1a10a0a39c0764442d3145dec to your computer and use it in GitHub Desktop.
Save primaryobjects/e6e9f7c1a10a0a39c0764442d3145dec to your computer and use it in GitHub Desktop.
A promise chain with setTimeout in javascript.
// Demo http://jsbin.com/qevetiqavu/edit?js,output
var one = function(i) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`setTimeout ${i}`);
if (i < 0) {
reject(i);
}
else if (i >= 5) {
resolve(i);
}
else {
return one(i + 1)
.then(i => { resolve(i); })
.catch(err => { reject(err); });
}
}, 1000);
});
}
var two = function(i) {
return one(i)
.then(i => {
return i * 2;
})
.catch(err => { throw err; });
}
two(1)
.then(i => console.log(`Done ${i}`))
.catch(err => console.log(`Error: ${err}`));
// A slight variation of the first example, where we pass in a value.
// Demo http://jsbin.com/yegovopuya/1/edit?js,output
var one = function(i, original) {
original = original || i;
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`setTimeout ${i}`);
if (i < 0) {
reject(i);
}
else if (i >= original + 4) {
resolve(i);
}
else {
return one(i + 1, original)
.then(i => { resolve(i); })
.catch(err => { reject(err); });
}
}, 1000);
});
}
var two = function(i) {
i = 100 + i;
return one(i)
.then(i => {
return i * 2;
})
.catch(err => { throw err; });
}
two(1)
.then(i => console.log(`Done ${i}`))
.catch(err => console.log(`Error: ${err}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment