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.

2

3 Answers 3

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 !

Sign up to request clarification or add additional context in comments.

1 Comment

@Sultan does it answers your question ?
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 

});

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.