I am facing a problem when calling multiple post requests at the same time. I need them to be in sequence, but they get on the API in random order. How can I ensure a sequence order by using http method on JavaScript?
Here is an example of what I am doing:
for( var i = 0; i < result.length; i++ ) {
$scope.update(result[i]);
}
$scope.update = function(results) {
$http({
method: 'POST',
url: Config.serverUrl,
data: JSON.stringify(results),
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
if ( response.data.status === "OK") {
$scope.error = null;
$scope.success = "Banco atualizado!";
} else {
$scope.error = response.data.message;
$scope.success = null;
}
$scope.searchTimeout();
}, function (response) {
$scope.error = "Banco atualizado! (erro baddata)";
$scope.success = null;
});
};
UPDATE
Example working with two for
loops and using promise
as suggested by @TJCrowder:
$scope.myFunc = function(results) {
return new Promise(function(resolve) {
resolve($scope.update(results));
});
};
var p = Promise.resolve();
for( var j = 0; j < result[3].length; j++ ){
for( var i = 0; i < result[4].length; i++ ){
p = p.then($scope.myFunc.bind($scope, results));
}
}