Join 2 'threads' in javascript

前端 未结 6 1478
时光取名叫无心
时光取名叫无心 2021-01-05 06:44

If I have an ajax call off fetching (with a callback) and then some other code running in the meantime. How can I have a third function that will be called when both of the

6条回答
  •  误落风尘
    2021-01-05 07:09

    Daniel's solution is the proper one. I took it and added some extra code so you don't have to think too much ;)

    function createNotifier() {
        var counter = 2;
        return function() {
            if (--counter == 0) {
                // do stuff
            }
        };
    }
    
    var notify = createNotifier();
    var later = function() {
        var done = false;
        // do stuff and set done to true if you're done
        if (done) {
            notify();
        }
    };
    
    function doAjaxCall(notify) {
        var ajaxCallback = function() {
            // Respond to the AJAX callback here
            // Notify that the Ajax callback is done
            notify();
        };
        // Here you perform the AJAX call action
    }
    
    setInterval(later, 200);
    doAjaxCall(notify);
    

提交回复
热议问题