我覺得你還是可以做到這一點異步。首先,你需要獲得所有屬性你的對象:
//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);
這會工作,這取決於你的'做something'是幹什麼的,如果它做動畫或'get's什麼它不可能奏效。另外,不要使用'Object'作爲變量,它是一個保留字,很多 – Blowsie
如果你正在'做些什麼'通過ajax發出這些HTTP請求,確保你要同步執行它們。換句話說,確保在執行'res(resultArray)'之前獲得響應。另外請記住,HTTP請求是昂貴的,在1個HTTP請求中將對象發送到服務器,然後將結果數組發送回服務器會更有效嗎? –
@Blowsie是的,我的示例中使用了變量名稱。這不工作,因爲我正在發出一個HTTP請求,並在我得到響應之前繼續前進。 – Rob