0

I am fairly new to jquery promises. I would like to ask if this case is possible:

I have 2 ajax calls and I'm using .then() to chain the two of them. This is what i would like to do:

ajaxCall1().then(ajaxCall1).done(functionCallHere);

I can use the response of ajaxCall1 in ajaxCall2 which is what I really intend to do. However, what I want in the finality is to use both ajaxCall1's and ajaxCall2's responses in the functionCallHere.

I have searched for similar questions here, and I have never found one. So.. is it possible to access the ajaxCall1's response in the functionCallHere ? if yes, how do I do it? Is it similar to how $.when(ajax1, ajax2).done(function(r1, r2)) work - like if you put 2 parameters in your function, it is automatically interpreted as response1 and response2?

Also, I am trying to not use .when() here since I don't want the calls to run asynchronously or to fork them. as much as possible I just want to chain them. Of course, If it's the only way, then I can revert back to using it.

Thank you very much! :)

  • 1
    did you tried? `ajaxCall1().then((response) => {ajaxCall2(); functionCallHere(response);})` – hasan05 Jan 31 '20 at 04:46
  • for sure, you can call your `functionCallHere` inside then. and also you know you can pass your response to a function. – hasan05 Jan 31 '20 at 04:48
  • Thank you! yes this was my first approach. I was just wondering if there is such a way that you can do something like this: ``` .then(ajx2).then(ajx3).then(ajx4).done(functionHere) ``` and `functionHere` can use all ajax call responses such that it works same as `.$.when()`'s `function(rs1, rs2, rs3)` that way it would look cleaner. but yes, your answer works! so thank you! – user8237911 Jan 31 '20 at 06:29

1 Answers1

1

You can do by nesting.

ajaxCall1()
    .then((response) => {
         ajaxCall2()
             .then((response2) => { 
                 functionCallHere(response);
         })
    })

or you can define variable before all ajax calls.

var response1;
var response2;
ajaxCall1()
    .then((response) => {
         response1 = response; 
         ajaxCall2()
             .then((response2) => { 
                 response2 = response2; 
         })
    })
   .done(functionCallHere(response1)); // or other variable you want to pass.

one more solution you can try ->

async function yourFunction() {
    var response1 = await ajaxCall1();
    var response2 = await ajaxCall2();
    functionCallHere(response1); // or other variable you want to pass.
}

note: dont miss async before function;

hasan05
  • 904
  • 5
  • 22
  • 1
    Ohhh.. The solution I used was similar to the second one (defining variables before all ajax calls). Thank you! this really helped me! i'm gonna have to read about the `async` and `await` keywords before I use them - like I said, I'm entirely new to this concept. Thank you for the suggestions! – user8237911 Jan 31 '20 at 08:29