Created
February 5, 2021 10:40
-
-
Save yeomann/ac528cbe55942cde11264bd9106a446c to your computer and use it in GitHub Desktop.
Node Asycn 1 by 1 job
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 { once, EventEmitter } = require('events'); | |
const myEmitter = new EventEmitter(); | |
let isJobCurrentlyRunning = false; | |
async function doAsyncJobsOneByOne(id) { | |
if (!isJobCurrentlyRunning) { | |
doJob(id); | |
} else { | |
await once(myEmitter, 'jobdone'); | |
doJob(id); | |
} | |
} | |
function doJob(id) { | |
isJobCurrentlyRunning = true; | |
setTimeout(() => { | |
console.log('done', id) | |
isJobCurrentlyRunning = false; | |
myEmitter.emit('jobdone') | |
}, randInt(1000)) | |
} | |
for (let i = 0; i < 3; i++) { | |
setTimeout((() => { | |
doAsyncJobsOneByOne(i + 1) | |
}).bind(i)) | |
} | |
console.log('binded 3') | |
// helper | |
function randInt(max) { | |
var rand = Math.random() * max; | |
rand = Math.floor(rand); | |
return rand; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment