Skip to content

Instantly share code, notes, and snippets.

@andrIvash
Created February 8, 2019 12:47
Show Gist options
  • Save andrIvash/18d28ebcad13b86d73d46040ab373842 to your computer and use it in GitHub Desktop.
Save andrIvash/18d28ebcad13b86d73d46040ab373842 to your computer and use it in GitHub Desktop.
Like multithreading Node
const crypto = require('crypto')
const arr = new Array(200).fill('something')
function processChunk() {
if (arr.length === 0) {
// code that runs after the whole array is executed
} else {
console.log('processing chunk');
// pick 10 items and remove them from the array
const subarr = arr.splice(0, 10)
for (const item of subarr) {
// do heavy stuff for each item on the array
doHeavyStuff(item)
}
// Put the function back in the queue
setImmediate(processChunk)
}
}
processChunk()
function doHeavyStuff(item) {
crypto.createHmac('sha256', 'secret').update(new Array(10000).fill(item).join('.')).digest('hex')
}
// This is just for confirming that we can continue
// doing things
let interval = setInterval(() => {
console.log('tick!')
if (arr.length === 0) clearInterval(interval)
}, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment