Skip to content

Instantly share code, notes, and snippets.

@wjx
Created December 18, 2016 12:35
Show Gist options
  • Save wjx/d7c101fd8e141f93066eacc24096e73f to your computer and use it in GitHub Desktop.
Save wjx/d7c101fd8e141f93066eacc24096e73f to your computer and use it in GitHub Desktop.
Alternative solution for EloquentJavaScript exercise 17.2
function all(promises) {
return new Promise(function(success, fail) {
// Your code here.
function promiseThen(i) {
return promises[i].then(function(res) {
//we should return the res here.
//push into results here won't work, since
//promises here settles at different time
//and elements in results will be out of order.
return res;
}, fail);
}
function createPtFunc(pt) {
return function() {
//Instead of just return pt, push into results
//here.
return pt.then(function(res) {
results.push(res);
});
};
}
var results = [];
var sequence = Promise.resolve();
for (var i = 0; i < promises.length; i++) {
var pt = promiseThen(i);
sequence = sequence.then(createPtFunc(pt));
}
sequence.then(function() {
success(results);
});
/*
var results = [];
var pro = Promise.resolve();
promises.push(pro);
promises.reduce(function(sequence, promise) {
return sequence.then(function() {
return promise;
}).then(function(res) {
if (promise == pro)
success(results);
else
results.push(res);
}, fail);
}, Promise.resolve());
*/
});
}
// Test code.
all([]).then(function(array) {
console.log("This should be []:", array);
});
function soon(val) {
return new Promise(function(success) {
setTimeout(function() { success(val); },
Math.random() * 500);
});
}
all([soon(1), soon(2), soon(3)]).then(function(array) {
console.log("This should be [1, 2, 3]:", array);
});
function fail() {
return new Promise(function(success, fail) {
fail(new Error("boom"));
});
}
all([soon(1), fail(), soon(3)]).then(function(array) {
console.log("We should not get here");
}, function(error) {
if (error.message != "boom")
console.log("Unexpected failure:", error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment