2013-06-03 70 views
0

我有一個Object,我想循環並針對一系列IF語句運行。每個IF語句使得HTTP RequestHTTP Request的結果被推送到Array。我需要在循環對象之後執行一個函數。Javascript如何在運行多個IF語句後獲得價值

如何在循環和IF語句完成後才執行函數?

代碼:

function myFunction(Object, res) { 
    var resultArray; 
    for (var obj in Object) { 
     if (something is true) { 
      //do something 
      resultArray.push(result) 
     } 
    } 
    //After the for loop is confirmed finished, do callback 
    res(resultArray) 
} 
+1

這會工作,這取決於你的'做something'是幹什麼的,如果它做動畫或'get's什麼它不可能奏效。另外,不要使用'Object'作爲變量,它是一個保留字,很多 – Blowsie

+0

如果你正在'做些什麼'通過ajax發出這些HTTP請求,確保你要同步執行它們。換句話說,確保在執行'res(resultArray)'之前獲得響應。另外請記住,HTTP請求是昂貴的,在1個HTTP請求中將對象發送到服務器,然後將結果數組發送回服務器會更有效嗎? –

+0

@Blowsie是的,我的示例中使用了變量名稱。這不工作,因爲我正在發出一個HTTP請求,並在我得到響應之前繼續前進。 – Rob

回答

1

我覺得你還是可以做到這一點異步。首先,你需要獲得所有屬性你的對象:

//Gather up all the properties; 
var properties = []; 
for(var property in object) if(object.hasOwnProperty(property) { 
    properties.push(property); 
} 

//Array of results 
var resultsArray = []; 


//This is a named, self-invoked function that basically behaves like a loop. The 
//loop counter is the argument "i", which is initially set to 0. The first if 
//is basically the loop-termination condition. If i is greater than the 
//total number of properties, we know that we're done. 
// 
//The success handler of the ajax call is where the loop is advanced. This is also 
//where you can put your if condition to check if something is true, so that you 
//can insert the data into the results array. At the end of the success handler, 
//you basically call the named self-invoked function, but this time with the 
//loop counter incremented. 
(function iterateOverProperties(i) { 
    if(i < properties.length) { 
     var property = properties[i]; 
     var value = object[property]; 

     //assuming jQuery just for demonstration 
     jQuery.ajax({ 
      url: "someurl", 
      data: value; 
      success: function(data) { 
       if(something is true) { 
        resultArray.push(data); 
       } 

       iterateOverProperties(++i); 
      } 
     }); 
    } else { 
     res(resultArray); 
    } 
})(0);