Created
July 11, 2020 19:06
-
-
Save lcherone/8ab76b783b384c8ae42a3d747014f46c to your computer and use it in GitHub Desktop.
js async queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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