Javascript - synchronizing after asynchronous calls

前端 未结 6 1618
北恋
北恋 2021-02-04 02:08

I have a Javascript object that requires 2 calls out to an external server to build its contents and do anything meaningful. The object is built such that instantiating an inst

6条回答
  •  隐瞒了意图╮
    2021-02-04 02:56

    Another way would be to have a sync point thanks to a timer. It is not beautiful, but it has the advantage of not having to add the call to the next function inside the callback.

    Here the function execute_jobs is the entry point. it take a list of data to execute simultaneously. It first sets the number of jobs to wait to the size of the list. Then it set a timer to test for the end condition (the number falling down to 0). And finally it sends a job for each data. Each job decrease the number of awaited jobs by one.

    It would look like something like that:

    var g_numJobs = 0;
    
    function async_task(data) {
        //
        // ... execute the task on the data ...
        //
    
        // Decrease the number of jobs left to execute.
        --g_numJobs;
    }
    
    function execute_jobs(list) {
        // Set the number of jobs we want to wait for.
        g_numJobs = list.length;
    
        // Set the timer (test every 50ms).
        var timer = setInterval(function() {
            if(g_numJobs == 0) {
                clearInterval(timer);
                do_next_action();
            }
        }, 50);
    
        // Send the jobs.
        for(var i = 0; i < list.length; ++i) {
            async_task(list[i]));
        }
    }
    

    To improve this code you can do a Job and JobList classes. The Job would execute a callback and decrease the number of pending jobs, while the JobList would aggregate the timer and call the callback to the next action once the jobs are finished.

提交回复
热议问题