Skip to content

Instantly share code, notes, and snippets.

@Momijiichigo
Last active January 31, 2022 04:23
Show Gist options
  • Save Momijiichigo/e76ce40fde5b304c043df8ae7f39a0af to your computer and use it in GitHub Desktop.
Save Momijiichigo/e76ce40fde5b304c043df8ae7f39a0af to your computer and use it in GitHub Desktop.
waitExec

Wait Exec

A simple way to make process wait for multiple conditions.

This is similar to Promise.all but WaitExec allows you to register conditions flexibly.

It's useful to export waitMe so that you can add conditions from other files.

// want to run this right after everything is ready...
function init() {
console.log('init!')
}
// you can export `waitMe` so that `init` can wait for processes in other files
const { waitMe } = waitExec(init);
const { okToGo } = waitMe()
addEventListener('load',()=>
okToGo() // I'm ok to call `init`
);
(()=>{
// fileB.ts
const { okToGo } = waitMe()
/* some process that takes long... */
okToGo() // I'm ok to call `init`
})();
type Listener = () => void
/**
* @param func process to run when all waiting factors are ready to go
*/
export const waitExec = (func: Listener) =>{
const waiting: boolean[] = []
let count = 0
/**
* tells the process to wait till all factors run `okToGo`
*/
const waitMe = () =>{
const i = count++
waiting.push(false)
/**
* tells the process that you are no longer waiting
*/
const okToGo = () =>{
waiting[i] = true
if(waiting.every(v=>v)) func()
}
return {
okToGo
}
}
return {
waitMe
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment