Skip to content

Instantly share code, notes, and snippets.

@adrianvlupu
Last active March 17, 2017 14:49
Show Gist options
  • Save adrianvlupu/e9d54d3585163c1d508c3ba1624467e0 to your computer and use it in GitHub Desktop.
Save adrianvlupu/e9d54d3585163c1d508c3ba1624467e0 to your computer and use it in GitHub Desktop.
Sequential promise resolve
var f1 = () => {
return new Promise((resolve, reject) =>{
setTimeout(()=>{
resolve('p1 complete');
}, 1000);
});
};
var f2 = () => {
return new Promise((resolve, reject) =>{
setTimeout(()=>{
resolve('p2 complete');
}, 1000);
});
};
[f1, f2].reduce((x, y)=>{
console.log(x,y);
return x.then(data => {
console.log(data);
return y();
});
}, Promise.resolve()).then(last => {
console.log(last);
});
var p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('p1');
resolve();
}, 1000);
});
var p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('p2');
resolve('a');
}, 2000);
});
[p1,p2].reduce((x, y)=>{
return x.then(()=>{
return y;
});
}, Promise.resolve())
.then(()=>{
console.log('finished all');
});
//https://remysharp.com/2015/12/18/promise-waterfall
var guid = 0;
function run() {
guid++;
var id = guid;
return new Promise(resolve => {
// resolve in a random amount of time
setTimeout(function () {
console.log(id);
resolve(id);
}, (Math.random() * 1.5 | 0) * 1000);
});
}
var promises = Array.from({ length: 10 }).reduce(function (acc) {
return acc.then(function (res) {
return run().then(function (result) {
res.push(result);
return res;
});
});
}, Promise.resolve([]));
promises.then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment