I have a loop, iterating over an object that runs a function with a callback. The problem is I want the callback to only run after all the items have gone through the loop... not each and every time.

$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
}
有帮助吗?

解决方案

There is also a bug x = 3
'=' is assignment '==' is equality without type comparison.

$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 ) ;

其他提示

Edit:

This won't fire the callback unless there was a matched item and only fires after finished iterating:

$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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top