0

hey people I'm facing an issue and I can't find a solution. I'm trying to chain 2 rest call functions and after them use a function which uses the objects returned from both of them. For some reason something is not working I think its something to do with the syntax I wrote. I would like to understand why my code:

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>

    <script>
      var users = [];
      var user = null;

      function restCallA() {
        $.ajax({
          url: "https://reqres.in/api/users?page=2",
          type: "GET",
          success: function(response) {
            users = response.data;
          }
        });
      }
      function restCallB() {
        $.ajax({
          url: "https://reqres.in/api/users/2",
          type: "GET",
          success: function(response) {
            user = response.data;
          }
        });
      }
      function myFun() {
        users.push(user);
        console.log(users);
      }
      restCallA()
        .then(restCallB())
        .then(myFun());
    </script>
  </body>
</html>

error:

test.html:38 Uncaught TypeError: Cannot read property 'then' of undefined

0

1 Answer 1

1

Both restCallA and restCallB must return the result of each of their $.ajax calls, then you can chain them using then().

Another issue is that you are invoking restCallB and myFun instead of passing the functions in as parameters:

restCallA()
        .then(restCallB())
        .then(myFun());

should be:

restCallA()
        .then(restCallB)
        .then(myFun);
Sign up to request clarification or add additional context in comments.

5 Comments

I'm not entirely sure that's how it works. Where is the promise in ajax?
@denat how can I use the result of each ajax call if not inside the ajax call itself? I mean when i do restCallA(data).then(restCallB).then(myFun) I can't pass the data of the first function.... same for the second one
@hindi1991 both restCallB and myFun can accept a data parameter which will contain the result of the previous ajax request
@AnuragSrivastava you can manipulate the underlying Promise using jqXHR.then(...). Source: http://api.jquery.com/jquery.ajax
@denat I understand but how tdo I write it down as a syntax? since I got no () on thr second function when I use .then chaining

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.