Created
August 16, 2018 01:03
-
-
Save nidate/001a6cc0ec97bdbdc0f0bcb6796232ab to your computer and use it in GitHub Desktop.
generatorの並列実行と直列実行
This file contains 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 co = require('co'); | |
// 0‾1秒の処理 | |
const proc = function*() { | |
const wait = Math.random(); | |
return new Promise(resolve => | |
setTimeout(function() { | |
return resolve(wait); | |
}, wait * 1000) | |
); | |
}; | |
co(function*() { | |
//並列実行 | |
console.time('parallel'); | |
const parallel = yield Array.from({ length: 10 }).map(() => { | |
return proc(); | |
}); | |
console.timeEnd('parallel'); | |
console.log(parallel); | |
//直列実行 | |
console.time('serial'); | |
const serial = []; | |
for (let i = 0; i < 10; i++) { | |
serial.push(yield proc()); | |
} | |
console.timeEnd('serial'); | |
console.log(serial); | |
}) | |
.catch(err => { | |
console.error(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment