Skip to content

Instantly share code, notes, and snippets.

@yeomann
Created February 5, 2021 10:40
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 yeomann/ac528cbe55942cde11264bd9106a446c to your computer and use it in GitHub Desktop.
Save yeomann/ac528cbe55942cde11264bd9106a446c to your computer and use it in GitHub Desktop.
Node Asycn 1 by 1 job
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