简体   繁体   English

javascript这个顺序异步任务问题怎么解决?

[英]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.在下面的代码片段中,任务是 object 的任务,function 的定义应该与预期的 output 相匹配。

    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. function executeTasks将采用顶部所示示例的任务列表以及回调。 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. function 的本质是任务将在考虑所有依赖关系的情况下执行,一旦所有任务都执行完毕,传递的回调应该调用。 The expected output is an example how the result will be for that given task list.预期的 output 是给定任务列表的结果示例。

Use rxjs , forkJoin might help you do it gracefully.使用rxjsforkJoin可能会帮助您优雅地完成它。 https://rxjs.dev/api/index/function/forkJoin https://rxjs.dev/api/index/function/forkJoin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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