Reputation: 978
I am using Parse.com in my project and I noticed something very weird that is preventing me from implementing what I want. This code:
(function() {
console.log('A');
Parse.Cloud.run('getCarMakes', {}, {
success: function(results) {
console.log('B');
for (var i = 0; i < results.length; i++) {
$scope.makes.push(results[i]);
}
},
error: function() {
console.log('C');
}
});
console.log('D');
for (var i = 0; i < $scope.makes.length; i++) {
console.log($scope.makes).get('Make');
}
})();
The console Output is: A B D C
How come D comes before C? What Can I do about it?
Upvotes: 0
Views: 112
Reputation: 3741
Michael Cole is right. Also depending on your implementation, since C is running in the error block, you can run D in there as well and it will run before C.
(function () {
console.log('A');
Parse.Cloud.run('getCarMakes', {}, {
success: function (results) {
console.log('B');
for (var i=0;i<results.length;i++){
$scope.makes.push(results[i]);
}
},
error: function () {
console.log('D');
for (var i=0;i<$scope.makes.length;i++){
console.log($scope.makes).get('Make');
}
console.log('C');
}
});
})();
Upvotes: 2
Reputation: 16217
Matansab, you'll need to start thinking "asynchronously".
The short answer is: Put "D" in the "success" callback.
(function () {
console.log('A');
Parse.Cloud.run('getCarMakes', {}, {
success: function (results) {
console.log('B');
for (var i=0;i<results.length;i++){
$scope.makes.push(results[i]);
}
console.log('D');
for (var i=0;i<$scope.makes.length;i++){
console.log($scope.makes).get('Make');
}
},
error: function () {
console.log('C');
}
});
console.log("This will always run right after A");
})();
The "success" function is a "callback". Callbacks are a common pattern in Javascript. They are "called" after an async function returns. Async functions are requests to things like network or disk, that take so long Javascript shouldn't wait. Once the async function is ready, it calls the "callback".
You can learn more about javascript callbacks by googling, or just try here
Upvotes: 2
Reputation: 176
it's not running sequentially because your success and error functions are callbacks. They're not executed until the Parse.com library actually invokes them.
Upvotes: 0