0

I am trying to use the ajax function to assign the first task to the back end, and continue using another ajax function to assign the second job to the back end when the first task is done.

function fun1() {
    $.ajax({
        type:"POST",
        async:false,
        url: ...,
        success:function() {
            alert(0);
            fun2();
            alert(4);
        }
    });
}

function fun2() {
    $.ajax({
        type:"POST",
        async:false,
        url: ...,
        success:function() {
            alert(1);
            fun3();
            alert(3);
        }
    });
}

function fun3(){
    alert(2);
}

I expected the alert result should be 0 1 2 3.

However, I got the result 0 4 1 2 3

async seems not work here. Can anyone know how to do that?

Thanks

F.C. Hsiao
  • 37
  • 1
  • 1
  • 5

2 Answers2

0

you can try and use Promise.all so in your case it will look like this

const ajax1=$.ajax({
        type:"POST",
        async:false,
        url: ...,
        success:
    });
const ajax2=$.ajax({
        type:"POST",
        async:false,
        url: ...,
        success: 
    });
const ajax3=$.ajax({
            type:"POST",
            async:false,
            url: ...,
            success: 
        });
// here you can put your ajax calls in the order order you want
    const promises=Promise.all([ajax1,ajax2,ajax3])

However if the order of execution is very important to you for whatever reason you can us a loop like this

async function getresponse() {
    const promises = [ajax1, ajax2 ,ajax3]
    for (let promise of promises) {
        try {
            const resp= await promise
            console.log(resp)
        } catch(err) {   
            console.log(err.message)
        }
    }
}

getresponse()
Milton
  • 970
  • 4
  • 13
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
0

The log order shows you exactly what working with async code is like without using modern features like async/await.

You first call fun1, which upon completing the async request logs 0 and then calls fun2 which starts the next async request, but since it is async, execution goes back to the success handler in fun1 and it logs 4. Once the async request is done in fun2 it's success handler is called which logs the rest.

To get the effect you want, you need to wait for the async effect from fun2 to be done before proceeding, see this answer for how to do that https://stackoverflow.com/a/16045729/4707926, something like this:

// First modify fun2 to return the result of $.ajax

// Then inside the success handler for fun1
alert(0);
fun2()
    .then(() => {
        alert(4)
    })
    .catch((error) => {
        alert(error)
    })
Milton
  • 970
  • 4
  • 13