Join 2 'threads' in javascript

前端 未结 6 1436
时光取名叫无心
时光取名叫无心 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:04

    You can do this easily with Google's Closure library, specifically goog.async.Deferred:

    // Deferred is a container for an incomplete computation.
    var ajaxFinished = goog.async.Deferred();
    
    // ajaxCall is the asynchronous function we're calling.
    ajaxCall( //args...,
        function() {  // callback
          // Process the results... 
          ajaxFinished.callback();  // Signal completion 
        }
    );
    
    // Do other stuff...
    
    // Wait for the callback completion before proceeding
    goog.async.when(ajaxFinished, function() {
        // Do the rest of the stuff...
    });
    

    You can join multiple asynchronous computations using awaitDeferred, chainDeferred, or goog.async.DeferredList.

提交回复
热议问题