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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.