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 | |
| } | |
| } |