Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Created Jan 26, 2021
Embed
What would you like to do?
var waitall = {
defer: [],
final: null
}
// will make sure to call `waitall.final` when all `waitall.defer` has cleared
function defer (fn) {
waitall.defer.push(fn)
return function (...args) {
var result = fn(...args)
waitall.defer.shift() // self
if (waitall.final && waitall.defer.length === 0) {
setTimeout(waitall.final)
waitall.final = null // for re-used lambda, this resets the state for next invoke
}
return result
}
}
// ensure `fn` is called when `waitall.defer` is empty
function final (fn) {
waitall.final = fn
if (waitall.final && waitall.defer.length === 0) {
setTimeout(waitall.final)
waitall.final = null // for re-used lambda, this resets the state for next invoke
}
}
module.exports = { final, defer }
/**
const { final, defer } = require('./defer.js')
function dosomething (n) {
console.log(n, 'start')
setTimeout(defer(function () {
console.log(n, 'end')
}), n * 1000)
}
dosomething(1)
dosomething(2)
dosomething(3)
dosomething(4)
final(function () { console.log('exit') })
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment