Skip to content

Instantly share code, notes, and snippets.

@waghcwb
Last active March 29, 2019 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waghcwb/daf95142c7964658c55dc0be8ef7188f to your computer and use it in GitHub Desktop.
Save waghcwb/daf95142c7964658c55dc0be8ef7188f to your computer and use it in GitHub Desktop.

Await a global variable or an array of variables to be defined.


With Promises and inner methods suppport.

function awaitGlobal(keys, wait = 300) {
return Promise.all(
[].concat(keys).map(key => {
return new Promise((resolve, reject) => {
let timer
const loop = () => {
if (key.indexOf('.') > -1) {
try {
let __key = key.split('.')[0]
if (root[__key]) {
const __eval = eval(key.replace(/[(){};,]/g, ''))
if (__eval) {
resolve(__eval)
clearInterval(timer)
}
}
} catch (err) {
reject(err)
}
} else if (root[key]) {
resolve(root[key])
clearInterval(timer)
}
}
timer = setInterval(loop, wait)
loop()
})
})
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment