循环中的回调函数只触发一次

时间:2014-05-13 16:05:52

标签: javascript angularjs loops callback

我有一个循环,遍历一个运行带回调函数的对象。问题是我希望回调只在所有项目都经过循环之后运行...而不是每次都这样。

$scope.myArray = [];
Object.keys($scope.obj).forEach(function(key) {
    var curNode = $scope.obj[key];

    if ( curNode ) {
        if ( x = 3 ) {
            $scope.myArray.push(curNode);
            myFunction({
                //do something before the callback,
            }, myCalback( myArray ) );
        }
    }
});

$scope.myCallback = function ( arry ) {
    //do something ONCE with arry
}

2 个答案:

答案 0 :(得分:0)

还有一个错误x = 3
' ='是作业' =='是没有类型比较的平等。

$scope.myArray = [];
Object.keys($scope.obj).forEach(function(key) {
var curNode = $scope.obj[key];

if ( curNode ) {
    if ( x == 3 ) {
        $scope.myArray.push(curNode);
        myFunction({
            //do something before the callback,
        });
    }
}
});

$scope.myCallback = function ( arry ) {
//do something ONCE with arry
}

$scope.myCalback( $scope.myArray ) ;

答案 1 :(得分:0)

修改

这不会触发回调,除非有匹配的项目,并且只在完成迭代后触发:

$scope.myArray = [];
var run = false;

Object.keys($scope.obj).forEach(function(key) {
    var curNode = $scope.obj[key];

    if ( curNode ) {
        if ( x == 3 ) {
            $scope.myArray.push(curNode);
            myFunction({
                //do something before the callback,

            }, function() {run = true} );
        }
    }
});

$scope.myCallback = function ( arry ) {
    //do something ONCE with arry

}

if (run) $scope.myCallback($scope.myArray);