Skip to content

Instantly share code, notes, and snippets.

@lujjjh

lujjjh/main.js Secret

Last active June 3, 2023 04:45
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 lujjjh/ff95a7a046cc271bb06d4fdfb4161197 to your computer and use it in GitHub Desktop.
Save lujjjh/ff95a7a046cc271bb06d4fdfb4161197 to your computer and use it in GitHub Desktop.
Simple job queue
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
Copy link

dispatch 里的 for 整的阳气啊

@lujjjh
Copy link
Author

lujjjh commented Jun 3, 2023

@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