環路

2016-11-10 39 views
1

所以每次迭代等待異步.done(),我有功能鎖定這樣的:環路

function getMainData() { 
    var dfd = $.Deferred(); 

    $.getJSON('My string that i pass', 
     function(result) { 
      if (result !== undefined) { 
       dfd.resolve(result); 
      } 
     }) 

    return dfd.promise() 
} 

function getSpecificData() { 
    var dfd = $.Deferred(); 

    var myArray = []; 

    for (var i = 0; i < 5; i++) { 
     getMainData().done(function(result) { 
      myArray.push(result) 

      dfd.resolve(myArray) //This is where I am lost. 
     }) 
    } 

    return dfd.promise() 
} 

getSpecificData().done(function(result) { 
    console.log(result); 
}) 

我想我知道,如果你把它們連在一起的承諾是如何工作的,但我不能讓for-loop在下一次迭代之前等待異步調用完成。

能有些幫助我嗎?

回答

2

一種用於環路具有延遲下一次迭代等待異步代碼的手段。

您可以通過使用一個被遞歸調用,而不是

function getMainData() { 
    return $.getJSON('My string that i pass'); 
} 

function getSpecificData() { 
    var myArray = [], def = new $.Deferred(); 

    (function rec(i) { 
     getMainData().done(function(result) { 
      myArray.push(result); 
      if (i < 5 && result !== undefined) { 
       console.log(i) 
       rec(++i); 
      } else { 
       def.resolve(myArray); 
      } 
     }); 
    })(0); 

    return def.promise(); 
} 

getSpecificData().done(function(result) { 
    console.log(result); 
}); 
+0

謝謝你的解決方案,這個結果不錯,而我其實是沒有考慮過遞歸方法。 – Zorken17

0

你試過沒有promise像:

var myArray = []; 
var cpt=0; 
var total=5; 

getMainData(); 
console.log(myArray); 

function getMainData() 
{ 
    $.getJSON('My string that i pass', function(result) { 
     if(cpt<total) 
     { 
      myArray.push(result); 
      cpt++; 

      getMainData(); 
     } 
    }) 
} 

希望這有助於。

1

而是應該推動所有的承諾到一個數組中,並等待所有到結束。

function getMainData() { 
    return $.getJSON('My string that i pass'); 
} 

function getSpecificData() { 
    var promiseArray = []; 

    for (var i = 0; i < 5; i++) { 
     promiseArray.push(getMainData()); 
    } 

    return $.when.apply($, promiseArray); 
} 

getSpecificData().done(function(result) { 
    console.log(result); 
}) 
+0

感謝一個很好的解決方案功能解決這個問題,但預期這是行不通的。我沒有從我所有的異步調用中獲取值。這意味着該循環不會等待異步調用。 – Zorken17

+0

@ Zorken17您可以使用參數變量獲得全額返還列表,而不是結果的變量 –