Skip to content

Instantly share code, notes, and snippets.

@kohendrix
Created November 30, 2018 07:33
Show Gist options
  • Select an option

  • Save kohendrix/d5b56e5382362c5d9ef450d5dde4c0c2 to your computer and use it in GitHub Desktop.

Select an option

Save kohendrix/d5b56e5382362c5d9ef450d5dde4c0c2 to your computer and use it in GitHub Desktop.
Simple tests of the Promise array execution order.
'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