0

I know there is already a question and answer found here, and this is where i got my example. The question is: Other question

Here is my code:

$('.start').click(function() {
    Generate();
})

function Generate()
{
    var _p = Promise.resolve();
    customers.forEach(customer =>
       _p = _p.then(() => AxCall(customer))
    );
}

function AxCall(v)
{
    $.ajax({
        url: '/generate/axgenerate/'+v['clm_customer_id'],
        complete: function() {
            count++;
            $('.completed').text(count);
        }
    })
}

The problem is that still here the ajax called are all fired at once. How can i do that the ajax call is fired one after the other, even if it failed or succeeded

Combinu
  • 882
  • 2
  • 10
  • 31

1 Answers1

1

You need to return the result of calling $.ajax. That return value is a jQuery promise:

function AxCall(v)
{
    return $.ajax({
//  ^^^^^^
    // ...

That way, the promise chain you're setting up with that forEach makes each step in the chain wait for the previous step to complete.

But since you want to continue whether the ajax succeeds or fails, you also need to convert rejection into fulfillment, so:

customers.forEach(customer =>
    _p = _p.then(() => AxCall(customer).catch(error => {});
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^
);

(You might report the error in some way, but the key thing here is that catch will catch the rejection and convert it to fulfillment [if you don't throw or return a promise that is/will be rejected.)


If you can use async functions and await, it's a bit simpler:

async function Generate()
{
    for (const customer of customers) {
        try {
            await $.ajax({
                url: '/generate/axgenerate/'+v['clm_customer_id'],
                complete: function() {
                    count++;
                    $('.completed').text(count);
                }
            });
        } catch (error) {
            // (perhaps report error here)
        }
    }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • yes now it is working.. my problem is the return from my ajax call. Thanks for the help. I will accept the answer. – Combinu Apr 28 '21 at 08:39