Skip to content

Instantly share code, notes, and snippets.

@lcherone

lcherone/script.js

Created Jul 11, 2020
Embed
What would you like to do?
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