mirror of
https://github.com/bendtherules/JSQuestions.git
synced 2026-08-19 00:30:48 +00:00
async scheduler 1
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
const TaskScheduler = require('./async-scheduler');
|
||||
|
||||
function wait(ms, label, shouldReject = false) {
|
||||
return () => new Promise((resolve, reject) => {
|
||||
console.log(`${label} started`);
|
||||
setTimeout(() => {
|
||||
console.log(`${label} finished`);
|
||||
shouldReject ? reject(new Error(label + ' failed')) : resolve(label + ' ok');
|
||||
}, ms);
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const scheduler = new TaskScheduler(2);
|
||||
|
||||
// By default paused; add tasks
|
||||
const p1 = scheduler.addTask(wait(300, 't1'));
|
||||
const p2 = scheduler.addTask(wait(200, 't2'));
|
||||
const p3 = scheduler.addTask(wait(100, 't3'));
|
||||
const p4 = scheduler.addTask(wait(50, 't4'));
|
||||
|
||||
console.log('Playing...');
|
||||
scheduler.play();
|
||||
|
||||
try {
|
||||
const results = await Promise.all([p1, p2, p3, p4]);
|
||||
console.log('All results:', results);
|
||||
} catch (err) {
|
||||
console.error('One failed:', err.message);
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user