0

我有一个Object我想循环并针对一系列 IF 语句运行的。每个 IF 语句都生成一个HTTP Request. 的结果HTTP Request被推入Array. 我需要在遍历对象后执行一个函数。

如何仅在 Looping 和 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)
}
4

1 回答 1

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);
于 2013-06-03T16:37:50.763 回答