2016-03-28 71 views
0

如何使用嵌套的帶有延遲的context.executeQueryAsync?下面是我的代碼,我會解釋正是我要找:使用上面的代碼結構在SharePoint Online中與延遲嵌套的context.executeQueryAsync

代碼

function getValues() { 
    var dfd = $.Deferred(function() { 

     context.executeQueryAsync(function() { 
      var navigationItem = []; 

      // First Loop 
      while (termEnumerator.moveNext()) { 

       // Push Parent Terms in navigationItem array 
       navigationItem.push({ "name": ""}); 

       // Get Sub Terms 
       context.executeQueryAsync(function() { 
        // Second Loop 
        while (termsEnum.moveNext()) { 
         // Push Sub Terms in navigationItem array 
         navigationItem.push({ "name": ""}); 
        } 
       }, function (sender, args) { 
        console.log(args.get_message()); 
       }); 
      } 

      dfd.resolve(navigationItem); 

     }, function (sender, args) { 
      console.log(args.get_message()); 
      dfd.reject(args.get_message()); 
     }); 
    }); 
    return dfd.promise(); 
} 

基本上我想獲取分類(條款&它的子項) 。最初,我創建了一個名爲navigationItem的數組,並遍歷所有術語。

在迭代過程中,首先,我將條件推入該數組中,並且隨着這一點,我還得到它的子條款(如果有的話)並將其推入同一個數組中。

我希望代碼不會進一步執行,直到第二個循環完成它的執行。這樣,我將有最後的數組,而將它返回到另一個函數。

回答

1

我想代碼不會進一步執行,直到第二個循環完成 它的執行。這樣我將有最後的數組,同時返回 另一個函數。

在這種情況下,您需要對每個executeQueryAsync有一個延遲。

然後,您需要創建一個總體等待所有異步方法完成的等待。

這是給你參考的樣例代碼:

(function ($) { 
    function executeQueryAsync(succeededCallback, failedCallback) 
    { 
     var period = Math.random() * 10000; 

     setTimeout(function() { 
      succeededCallback(); 
     }, period); 

    } 

    function forEachAsync(items, funcAsync, callback) 
    { 
     var count = 0; 

     var total = $.Deferred(); 

     function increment() 
     { 
      count++; 

      if(count == items.length) 
      { 
       total.resolve(); 
      } 
     } 

     for (var i = 0; i < items.length; i++) 
     { 
      (function exec(item) { 
       var deferred = $.Deferred(function (defer) { 
        funcAsync(function() { 
         callback(); 
         defer.resolve(); 
        }); 
       }); 

       deferred.done(function() { 
        increment(); 
       }); 
      })(items[i]); 
     } 

     return total.promise(); 
    } 

    var promise = forEachAsync([1, 2, 3, 4, 5], executeQueryAsync, function() { 
     console.log('call back executing + ' + Date.now()); 
    }); 

    promise.done(function() { 
     console.log("promise done"); 
    }); 
})(jQuery); 

enter image description here