0

How to post synchronous ajax request or how to set async as false in angular $http service.

Example of my service is

$http.post("qa.test.net/rest/customtableitem.profile.interests?format=json", JSONobject)

My controller is

for (var i = 0; i < Insert.length; i++) 
{
   if (Insert[i].ItemID == null) 
   {
      TestInterestService.insertTest(Insert[i]).success(function (data) {
      }).error(function (data) {
      });
    }
   }

In this data is getting inserted asynchronously not in order for that reason it is messing the order entered I want to insert in synchronous manner. Any suggestions

EDIT That did not solved my problem, I was looking for pointing to the service where we can sent async as false in request headers.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
Sultan
  • 133
  • 3
  • 21
  • Possible duplicate of [How to $http Synchronous call with AngularJS](http://stackoverflow.com/questions/13088153/how-to-http-synchronous-call-with-angularjs) – Angel Politis Jun 29 '16 at 07:09
  • You can also find the answer to your question here: http://stackoverflow.com/questions/26750814/how-to-make-synchronous-http-request-in-angular-js – Angel Politis Jun 29 '16 at 07:11

3 Answers3

1

As Ben Lesh pointed in his answer to How to $http Synchronous call with AngularJS you cannot perform not async call with $http service.

However as an alternative you can replace for loop to while loop, condition is until Insert array not empty, prior starting while loop create flag variable which would be boolean identifier that ajax success handler finished and next ajax can be sent. See code below with commented changes :

var flag = true;
var length = Insert.length;
 while (length){
  if(flag){ 
    var item = Insert[--length];
    // Set flag to false, until success executed
    flag = false;
    TestInterestService.insertTest(item).success(function( path ){
      // We are ready to perform next ajax, set flag to true.
      flag = true;
    }).error: function( path ){
       // Error or not we have to set flag to true to allow further iterating
       flag = true;
     }
  }
}

Good Luck !

Community
  • 1
  • 1
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
0

use async Library

link :https://www.npmjs.com/package/async

Example

 async.each(Insert, function (insert_record_objec, callback) {

    TestInterestService.insertTest(insert_record_objec).success(function (data) {
        callback();
    }).error(function (data) {
        callback();
    });


}, function (err) {
    // if any of the processing produced an error 

});
Qasem
  • 119
  • 1
  • 8
-1

For simple use cases, you can leverage promises, when one request has successfully resolved, only .then send another one

MyService.postMe().then(function(response) {
    MyService.postMeToo(response.data);
});
svarog
  • 9,477
  • 4
  • 61
  • 77