Skip to content

Instantly share code, notes, and snippets.

@Lin-Ya
Created August 11, 2023 03:02
Show Gist options
  • Save Lin-Ya/29cf2d930d5b7903c2d10f13747c4bec to your computer and use it in GitHub Desktop.
Save Lin-Ya/29cf2d930d5b7903c2d10f13747c4bec to your computer and use it in GitHub Desktop.
simple queue
const makeQueue = () => {
let currentTask = Promise.resolve();
// create a new promise so that errors can be bubbled
// up to the caller without being caught by the queue
return (fn) =>
new Promise((resolve, reject) => {
currentTask = currentTask
.then(() => fn())
.then(resolve)
.catch(reject);
});
};
const queue = makeQueue();
// function job(n) {
// return new Promise((resolve, reject) => {
// if (+n % 2 === 0) {
// reject();
// } else {
// setTimeout(() => {
// resolve();
// console.log(n + "__start");
// }, +n * 1000);
// }
// });
// }
const sequenceOfEvents = [];
const job = (name) => {
return new Promise((resolve, reject) => {
if (+name % 2 === 0) {
setTimeout(() => {
reject();
}, 1000);
} else {
sequenceOfEvents.push(`${name} started`);
setTimeout(
() => {
sequenceOfEvents.push(`${name} done`);
resolve();
},
+name > 2 ? 5000 : 0
);
}
});
};
(async function () {
try {
await Promise.allSettled([
queue(() => job("1")),
queue(() => job("2")),
queue(() => job("3")),
]);
} catch (error) {
} finally {
console.log(sequenceOfEvents);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment