mirror of
https://github.com/bendtherules/JSQuestions.git
synced 2026-08-18 13:53:51 +00:00
32 lines
877 B
JavaScript
32 lines
877 B
JavaScript
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);
|
|
}
|
|
})();
|