0

I have an html page which displays e-commerce orders. I select some of them with checkboxes, and create invoices using an ajax request to php server.

Now I want to create these invoices 3 by 3. So for example, if I have 4 invoices, I will make a ajax request 2 times, and show the process to user. Below is my code , I implemented async/await. However it is not working sync. I run below code for 4 invoices.

The output I expect should be in javascript console:

"Hello"
"Bye"
"Hello"
"Bye"

But it is printing to console:

"(2)Hello"
"(2)Bye"

What am I missing ? Here is the code:

  function processInvoices(){

  var arr_ordersToBeProcessed = [];

  let bulkCount = 3;
  let currCount = 0;
  let totalCount = jQuery("#div_orders").find('.invoiceCheckbox:checked').length;

  jQuery("#div_orders").find('.invoiceCheckbox').each(async function(i, obj) {

    let clickedOrder = $(obj).parent().parent().parent();

    if($(obj)[0].checked == true){

      let obj_singleOrder = {};

      obj_singleOrder.orderNumber = clickedOrder.find('.div_orderNumber').text();
      arr_ordersToBeProcessed.push(obj_singleOrder);

      currCount++;

      if(currCount%3==0 || currCount==totalCount){
          console.log("hello");
          const data = await jQuery.ajax({
                 type: "POST",
                 url: "./_production/createInvoices.php",
                 data: {
                   orders: JSON.stringify(arr_ordersToBeProcessed)
                 }
           });
          arr_ordersToBeProcessed = [];
          console.log("bye");

          if(currCount==totalCount){
            alert("Completed!"); return;
          }
      }
    }
  });
}
KIKO Software
  • 15,283
  • 3
  • 18
  • 33
HOY
  • 1,067
  • 10
  • 42
  • 85
  • It prints `2 x hello` then waits `sync` for `await jQuery.ajax`, after that it prints `2 x bye`, so what is wrong here? – n-- Apr 09 '22 at 16:49
  • `async`/`await` doesn't make things *synchronous* (it's still `async`hronous), it makes them sequential. – Bergi Apr 09 '22 at 18:01

1 Answers1

0

You are misunderstanding what "await" does. It does not make your call synchronous. It simply lets you write Code differently so that multiple asynchronous function calls in a row do not cause you Code to cascade into hell.

If you want to achieve a synchronous http call using jquery it can be done by adding

async: false

(As described here How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request? ).

I would however strongly advise against using synchronous http calls since it will make your website unresponsive while the call is being answered.

GJohannes
  • 1,408
  • 1
  • 8
  • 14