Last active
February 15, 2019 18:54
-
-
Save fredyang/ea736a7b8293edf7a1a25c39c7d2fbbf to your computer and use it in GitHub Desktop.
a parallel wrapper function
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
//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