Created
November 30, 2018 07:33
-
-
Save kohendrix/d5b56e5382362c5d9ef450d5dde4c0c2 to your computer and use it in GitHub Desktop.
Simple tests of the Promise array execution order.
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
| 'use strict'; | |
| var p = console.log; | |
| var FS = require('fs'); | |
| // fs appendFile Promise wrapper | |
| function write(path, data){ | |
| return new Promise((res, rej) => FS.appendFile(path, data, err => | |
| err ? rej(err) : res(p(data, 'is done!')) | |
| )); | |
| } | |
| // forEach... | |
| exports.forEachTest = () => { | |
| var arr = [...Array(10).keys()].map(i => i.toString()); | |
| try { | |
| p('just forEach ==========='); | |
| arr.forEach(i => write(__dirname.concat('/', i, '.txt'), i)) | |
| p('done?'); | |
| } catch (e) { | |
| p(e); | |
| } | |
| } | |
| // Promise.all and map() | |
| exports.promiseAllTest = () => { | |
| var arr = [...Array(10).keys()].map(i => i.toString()); | |
| p('promise all ============'); | |
| Promise.all(arr.map(i => write(__dirname.concat('/', i, '.txt'), i))) | |
| .then(_ => p('done')) | |
| .catch(e => p(e)); | |
| } | |
| // Promise and reduce | |
| exports.promiseReduceTest = () => { | |
| var arr = [...Array(10).keys()].map(i => i.toString()); | |
| p('promise reduce ==========='); | |
| arr.reduce((acc, cur) => acc.then(_ => write(__dirname.concat('/', cur, '.txt'), cur)), Promise.resolve()) | |
| .then(_ => p('done')) | |
| .catch(e => p(e)); | |
| /* | |
| this is the equivalent of... | |
| Promise.resolve() | |
| .then(_ => write(PATH, 0)) | |
| .then(_ => write(PATH, 1)) | |
| .then(_ => write(PATH, 2)) | |
| ... | |
| */ | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment