Skip to content

Instantly share code, notes, and snippets.

@mishelen
Created November 16, 2018 14:21
Show Gist options
  • Save mishelen/67a43c353fdc5aa2af61459caa8ba113 to your computer and use it in GitHub Desktop.
Save mishelen/67a43c353fdc5aa2af61459caa8ba113 to your computer and use it in GitHub Desktop.
Suppose you want to do complex calculations in JavaScript without blocking the Event Loop. You could partition your calculations so that each runs on the Event Loop but regularly yields (gives turns to) other pending events. In JavaScript it's easy to save the state of an ongoing task in a closure
function asyncExec(func, load, jobs) {
let done = false;
let value;
const makeDone = () => done = true;
return new Promise((resolve) => {
function executor(cb) {
if (!done) {
value = cb();
setImmediate(executor.bind(null, cb));
} else {
resolve(value);
}
}
executor(func(makeDone, load, jobs));
});
}
const sum = (done, load, jobs) => {
let value = 0;
let currentJob = 1;
return function () {
let lastJob = currentJob + load < jobs ? currentJob + load : jobs;
for (; currentJob <= lastJob; currentJob++) {
value += currentJob;
}
if (currentJob === jobs + 1) {
done();
}
return value;
};
};
(async () => {
console.log(await asyncExec(sum, 5, 5));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment