Skip to content

Instantly share code, notes, and snippets.

@lcherone
Created July 11, 2020 19:06
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 lcherone/8ab76b783b384c8ae42a3d747014f46c to your computer and use it in GitHub Desktop.
Save lcherone/8ab76b783b384c8ae42a3d747014f46c to your computer and use it in GitHub Desktop.
js async queue
const queue = []
Object.defineProperty(queue, 'push', {
configurable: true,
enumerable: false,
writable: true,
value: function (...args) {
console.log('queue changed')
if (typeof args[0] === 'function') args[0]()
return Array.prototype.push.apply(this, args)
}
})
const data = []
async function getData() {
return data
}
async function setData(v, d) {
console.log((v === (data[Object.values(data).length - 1] || 0) + 1 ? 'in' : 'out of') + ' sync')
data.push(v)
}
function someEventTrigger(evtId) {
queue.push(async () => {
let data = await getData()
await setData(evtId, data)
})
// is async, happens so fast would be empty
console.log('data:', data)
}
// trigger lots of things
for (let i = 0; i < 10; i++) someEventTrigger(i)
// trigger on thing
document.write('<button onclick="someEventTrigger((data[Object.values(data).length - 1] || 0) + 1)">Trigger</button>')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment