简体   繁体   中英

How to solve this sequential async task problem in javascript?

In the below code snippet ths tasks are an object of tasks and the function defination should be such a way that the expected output should match.

    Let tasks = {
        ‘a’: {
            job: function(finish){
                setTimeout(() => {
                    console.log(‘A done’)
                    finish();
                }, 5000)
            },
            dependencies: []
        },
        ‘b’: {
            job: function(finish){
                setTimeout(() => {
                    console.log(‘B done’)
                    finish();
                }, 2000)
            },
            dependencies: []
        },
        ‘c’: {
            job: function(finish){
                setTimeout(() => {
                    console.log(‘C done’)
                    finish();
                }, 2000)
            },
            dependencies: [‘a’, ‘b’]
        },
        ‘d’: {
            job: function(finish){
                setTimeout(() => {
                    console.log(‘D done’)
                    finish();
                }, 1000)
            },
            dependencies: []
        },
        ‘e’: {
            job: function(finish){
                setTimeout(() => {
                    console.log(‘E  done’)
                    finish();
                }, 2000)
            },
            dependencies: [‘c’, ‘b’]
        },
    };

// implement a executeTasks function which can be invoked like below

executeTasks(tasks, function(){
    console.log(‘all done’);
})


function executeTasks(taskList, callback) {
    // write your code here
}

// Expected output

D done
B done
A done
C done
E done
All done

the function executeTasks will take a tasklist as shown example on the top and also a callback. The nature of the function is that the tasks will be executed with considering all the dependencies and once all tasks are executed the passed callback should invoke. The expected output is an example how the result will be for that given task list.

Use rxjs , forkJoin might help you do it gracefully. https://rxjs.dev/api/index/function/forkJoin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM