Last active
December 12, 2017 11:13
-
-
Save hoony-o-1/86644a331a450948c64ffb36dd9be287 to your computer and use it in GitHub Desktop.
Promise.series - Synchronous version of Promise.all
This file contains hidden or 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
| const PromiseSeries = (arr) => { | |
| if (arr.length > 1) { | |
| const target = arr[0] | |
| const rest = arr.slice(1) | |
| return target.then(() => PromiseSeries(rest)) | |
| } else { | |
| return arr[0] | |
| } | |
| } |
This file contains hidden or 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
| const test1 = () => { | |
| return new Promise((resolve, reject) => { | |
| setTimeout(() => { | |
| console.log('Done with test1') | |
| resolve() | |
| }, 1000) | |
| }) | |
| } | |
| const test2 = () => { | |
| return new Promise((resolve, reject) => { | |
| setTimeout(() => { | |
| console.log('Done with test2') | |
| resolve() | |
| }, 1000) | |
| }) | |
| } | |
| const failTest = () => { | |
| return new Promise((resolve, reject) => { | |
| setTimeout(() => { | |
| console.log('Fail with failTest') | |
| reject(new Error('Fail with failTest')) | |
| }, 1000) | |
| }) | |
| } | |
| PromiseSeries([test1(), test2()]) | |
| .then(() => console.log('All Done!')) | |
| .catch(err => console.error(err)) | |
| /** | |
| * 'Done with test1' | |
| * 'Done with test2' | |
| * 'All Done!' | |
| */ | |
| PromiseSeries([test1(), failTest(), test2()]) | |
| .then(() => console.log('All Done!')) | |
| .catch(err => console.error(err)) | |
| /** | |
| * 'Done with test1' | |
| * 'Error: Fail with failTest' | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment