-
-
Save lujjjh/ff95a7a046cc271bb06d4fdfb4161197 to your computer and use it in GitHub Desktop.
Simple job 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 = []; | |
let dispatching; | |
async function dispatch() { | |
if (dispatching) return; | |
dispatching = true; | |
for (let task; (task = queue.shift()); await Promise.resolve(task()).catch(console.error)); | |
dispatching = false; | |
} | |
function postJob(f) { | |
if (typeof f !== 'function') return; | |
queue.push(f); | |
dispatch(); | |
} | |
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); | |
postJob(async () => { await sleep(1000); console.log('foo'); }); | |
postJob(async () => { await sleep(1000); console.log('bar'); throw new Error(); }); | |
postJob(() => console.log('baz')); | |
postJob(() => console.log('qux')); |
@NoirVoider 回过头来看当时写复杂了,可以直接
let p = Promise.resolve();
const postJob = (f) => {
if (typeof f !== "function") throw new TypeError("f is not a function");
p = p.then(f).catch(console.error);
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
dispatch 里的 for 整的阳气啊