Skip to content

Instantly share code, notes, and snippets.

@syropian
Last active March 4, 2021 17:54
Show Gist options
  • Save syropian/097792f068eff03286e62ef5d06bb8b8 to your computer and use it in GitHub Desktop.
Save syropian/097792f068eff03286e62ef5d06bb8b8 to your computer and use it in GitHub Desktop.
Lets you queue up async tasks and executes them sequentially
const queueTask = (() => {
let pending = () => Promise.resolve();
const run = async (fn) => {
try {
await pending;
} finally {
return fn();
}
};
return (fn) => (pending = run(fn));
})();
@syropian
Copy link
Author

syropian commented Mar 4, 2021

Use like:

const wait = (ms) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

queueTask(async () => {
  console.log("This will take 2 seconds");
  await wait(2000);
});

queueTask(async () => {
  console.log("This will take 3 seconds");
  await wait(3000);
});

queueTask(async () => {
  console.log("This will take 1 second");
  await wait(1000);
});

queueTask(async () => {
    console.log("Donezo!");
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment