外部コマンドが大量に同時実行されるとシステムが不安定になるので同時実行数を制御するサンプル
インストール
npm i execa semaphore
モジュール定義
command.js
const execa = require('execa');
const semaphore = require('semaphore');
class Command{
constructor(num){
this.sem = semaphore(num || 1);
}
cmdAsync(cmdpath, cmdlist){
return new Promise((resolve, reject) => {
this.sem.take(() => {
execa(cmdpath, cmdlist).then(result => {
this.sem.leave()
resolve(result)
}).catch(e => {
this.sem.leave()
reject(e)
})
})
})
}
}
module.exports = Command
サンプル
const Command = require('./command.js')
const com = new Command()
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)
com.cmdAsync("sleep", ["1"]).then(console.log)