0

I have 2 different ajax post methods that both run on a loop (with each one finishing before the next one starts), before I was using async: false and everything worked fine, but it is now depreciated and throws errors. Is there an alternative method so that I can run the methods synchronously while still in my loop? I have tried wrapping each in their own function and calling using .done() but this keeps my post in the loop.

function postLoop() {
len = 3
backorderPayLoad = []
cancelPayLoad = []

for (var i = 0; i < len; i++) {
    backorder = {
        "quantity": 20,
        "note": "Backorder",
    }

    cancel = {
        "quantity": 20,
        "note": "Cancel",
    }

    backorderPayLoad.push(backorder);
    cancelPayLoad.push(cancel);


    $.ajax({
        url: myurl,
        method: 'POST',
        contentType: : "application/json",
        async: false,
        data: JSON.stringify(backorderPayLoad[i]),
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    })

    $.ajax({
            url: myurl2,
            method: 'POST',
            contentType: : "application/json",
            async: false,
            data: JSON.stringify(cancelPayLoad[i]),
            beforeSend: function(xhr, settings)
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    })
}
}
Jennifer Goncalves
  • 1,442
  • 1
  • 12
  • 29
user2168066
  • 627
  • 11
  • 21

1 Answers1

0

Example that builds a recursive promise chain based on passing an array to your postloop().

 let orders =[{..},{...},{...}];
 // initiialize
 postloop(orders).then(finalData => {
   // do something with final data after all requests completed
   console.log('Final', finalData);
 }).catch(err=>{ // use `fail()` if jQuery version < 3
    console.log('oops something wrong in at least one request');
 });

 function postloop(orders) {
   let finalData = [],
     orderIndex = 0;

   function completeRequests(res) {
     // push results of each set of requests to array
     finalData.push(res);
     orderIndex++;
     if (orderIndex < orders.length) {
       //  return another set of request promises to add to chain 
       return doRequests(orders[orderIndex]).then(completeRequests)
     } else {
       // and finally return array of data to resolve all promises
       return finalData;
     }

   }
   // return promise chain
   return doRequests(orders[orderIndex]).then(completeRequests);

 }

 // function will be called recursively in postloop() always returning promise
 function doRequests(order) {
   let backorder = $.extend({}, order);
   backorder.note = "Backorder";

   // return request promises
   return firstRequest().then(secondRequest)


   function firstRequest() {
     return $.ajax({
       url: '/echo/json/',
       method: 'POST',
       data: {
         json: JSON.stringify(backorder)
       }
     }).then(backorderResponse => {
       console.log('First request complete for id: ', backorder.id)
       return backorderResponse;
     });
   }

   function secondRequest(backorderResponse) {
     let cancel = {
       id: backorderResponse.id, // do something with data from first response,
       qty: backorderResponse.qty,
       note: 'Cancel'
     };

     return $.ajax({
       url: '/echo/json/',
       method: 'POST',
       data: {
         json: JSON.stringify(cancel)
       }
     }).then(cancelOrderResponse => {
       // do something with each of the 2 responses
       let combinedData = {
         cancel: cancelOrderResponse,
         backorder: backorderResponse
       };
       console.log('Second request complete for id: ', cancel.id)
       return combinedData;
     });
   }
 }

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150