Created
September 27, 2022 19:23
-
-
Save cesarvr/98498718414d787b6544397915526222 to your computer and use it in GitHub Desktop.
Simple Async Task Queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function task1() { | |
return new Promise((resolve) =>{ | |
setTimeout(() => { | |
console.log('doing some work on state 1') | |
resolve({completed: true, value: 1}) | |
}, 50) | |
}) | |
} | |
/* | |
* This function will fail two times, demonstrating how our task runner can handle failure and re-entry. | |
*/ | |
const task2 = function() { | |
let counter = 0 | |
return () => new Promise(function (resolve) { | |
setTimeout(() => { | |
let completed = false | |
counter = counter + 1 | |
console.log('doing some work on state 2, success: ', counter===3, counter) | |
if(counter === 3) { | |
completed = true | |
} | |
resolve({completed, value: 2, message:'great!!'}) | |
}, 2000) | |
}) | |
}() | |
function task3() { | |
return new Promise((resolve) =>{ | |
setTimeout(() => { | |
console.log('doing some work on state 3') | |
resolve({completed: true, value: 3}) | |
}, 10) | |
}) | |
} | |
let doWeHaveMoreTasks = (states) => states.length > 0 | |
let returnIncompletedTasksToTheQueue = (list_of_tasks, task, task_info) => { | |
if(!task_info.completed){ | |
list_of_tasks.unshift(task) | |
} | |
return list_of_tasks | |
} | |
async function task_manager(tasks){ | |
while(tasks.length > 0){ | |
const task = tasks.shift() | |
const task_info = await task() | |
tasks = returnIncompletedTasksToTheQueue(tasks, task, task_info) | |
console.log(`Task number: ${task_info.value} has been completed => ${task_info.completed}.` ) | |
console.log(`Additional info: ${JSON.stringify(task_info,null,4)}`) | |
} | |
} | |
const _tasks = [task1, task2, task3] | |
task_manager(_tasks) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment