Skip to content

Instantly share code, notes, and snippets.

@fredyang
Last active February 15, 2019 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredyang/ea736a7b8293edf7a1a25c39c7d2fbbf to your computer and use it in GitHub Desktop.
Save fredyang/ea736a7b8293edf7a1a25c39c7d2fbbf to your computer and use it in GitHub Desktop.
a parallel wrapper function
//run this in node.js, firefox only, not in browser chrome for now
const parallel = async (...items) => {
const temp = [];
for (const item of items) {
temp.push(await item);
}
return temp;
};
const someResult = async () => {
return new Promise((resolve, reject) => {
console.log('running someResult() ...');
setTimeout(() => {
console.log('someResult() is done');
resolve('hello');
}, 2000);
});
};
const anotherResult = async () => {
return new Promise((resolve, reject) => {
console.log('running anotherResult()...');
setTimeout(() => {
console.log('anotherResult() is done');
resolve('world');
}, 3000);
});
};
(async () => {
console.log('running test case');
const t0 = new Date()
const [p1, p2] = await parallel(someResult(), anotherResult());
const t1 = new Date()
console.assert(p1 == 'hello')
console.assert(p2 == 'world')
console.assert(t1 - t0 < 3010)
console.log(p1, p2, t1 - t0)
console.log('all assertion passed, someResult(), anoterResult() is executed in parallel')
})();
console.log('eof')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment