Last active
October 21, 2016 05:42
-
-
Save royling/b429f633dee301ced0ba5f1206afa30a to your computer and use it in GitHub Desktop.
Promise.all in short
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
// inline type declaration for ES6 Promise object | |
// see full at https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/es6-promise/es6-promise.d.ts | |
declare class Promise { | |
constructor(callback: (resolve: (value?: any) => void, reject: (reason?: any) => void) => void); | |
then(onFulfilled?: (any) => any, onRejected?: (any) => any|void); | |
} | |
const isPromise: (p:any) => boolean = p => typeof p === 'object' && typeof p.then === 'function'; | |
const promiseAll: (promises:any[]) => Promise = promises => new Promise((resolve, reject) => { | |
let results = [], | |
pendingCount = promises.length, | |
_resolve = (result, index) => { | |
results[index] = result; | |
if (--pendingCount === 0) { | |
console.log(`All resolved: ${results}`); | |
resolve(results); | |
} | |
}; | |
promises.forEach((promise, index) => { | |
/*if (!isPromise(promise)) { | |
console.log(`value at ${index} is not a promise, resolve to ${promise}`); | |
_resolve(promise, index); | |
} else { | |
promise.then(result => { | |
console.log(`promise ${index} resolved to ${result}`); | |
_resolve(result, index); | |
}, reject); | |
}*/ | |
// with Promise.resolve, this can be simple as: | |
Promise.resolve(promise).then(result => _resolve(result, index), reject); | |
}); | |
}); | |
// test | |
let promises:any[] = [ | |
0, | |
new Promise(resolve => setTimeout(() => resolve(1), 2000)), | |
new Promise(resolve => setTimeout(() => resolve(2), 1500)) | |
]; | |
promiseAll(promises).then(results => console.log(results)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment