Skip to content

Instantly share code, notes, and snippets.

@nidate
Created August 16, 2018 01:03
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 nidate/001a6cc0ec97bdbdc0f0bcb6796232ab to your computer and use it in GitHub Desktop.
Save nidate/001a6cc0ec97bdbdc0f0bcb6796232ab to your computer and use it in GitHub Desktop.
generatorの並列実行と直列実行
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