0

I need to chain up methods, checked :

1. JavaScript Chainable Method Delimma

2. Javascript chaining methods together

3. Chaining methods in Javascript

4. Javascript chaining methods and processing time

But these questions are not similar to mine. Here is my situation :

I have 2 methods: A(), B(). B() have to be executed after A() finished.

Here is my code:

index.html

$(document).ready(function(){

function A(){
    $.ajax({
        type: 'GET',
        url: "https://rickandmortyapi.com/api/character/",
        dataType: "json",
        success: function (data) {
            var results = data.results;

            $.map(results, function(v, i){
                var card = `
                <div class="card" id="${v.id}">
                <img class="card-img-top" src="${v.image}" alt="Card image cap">
                <div class="card-body">
                  <h5 class="card-title">${v.name}</h5>
                  <p class="card-text">${v.gender}</p>
                  <p class="card-epi">...</p>
                </div>
              </div>
                `;

                $(".movies").append(card);
            });


        },
        error: function(data){

        }
    });
}

function B(){
    $.ajax({
        type: 'GET',
        url: "https://rickandmortyapi.com/api/episode",
        dataType: "json",
        success: function (data) {
            var results = data.results;

            $.map(results, function(v, i){
                $("#"+v.id).find(".card-epi").text(v.name)
            });
        },
        error: function(data){
            console.log("errors in B()", data);
        }
    });
}

new Promise(function(resolve, reject){
    resolve(A);
}).then(function(result){
    B();
});
// A();
// B();
});

index.html

      <!DOCTYPE html>
          <html>

          <head>
              <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" />
          </head>

          <body>
              <div class="movies card-columns">

              </div>
          </body>
          <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
          <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
          <script src="movies.js"></script>

          </html>

I tried to use Promise, but it doesn't work for me.

Here is the JSFidlde : https://jsfiddle.net/franva/8vuussrz/

4 Answers 4

2

You're almost there. Just return the $.ajax( ... ) from your function A and it will work like this:

function A() {
  return $.ajax( ... );
}

A()
  .then(function() {
    B();
  });

$.ajax( ... ) already exposes promise-like API in jQuery. So you should directly be able to apply .then() on the result of A().

Sign up to request clarification or add additional context in comments.

Comments

1

try it:

$(document).ready(function () {
  function A() {
    var def = $.Deferred();
    $.ajax({
      type: 'GET',
      url: "https://rickandmortyapi.com/api/character/",
      dataType: "json",
      success: function (data) {
        var results = data.results;

        $.map(results, function (v, i) {
          var card = `
                  <div class="card" id="${v.id}">
                  <img class="card-img-top" src="${v.image}" alt="Card image cap">
                  <div class="card-body">
                    <h5 class="card-title">${v.name}</h5>
                    <p class="card-text">${v.gender}</p>
                    <p class="card-epi">...</p>
                  </div>
                </div>
                  `;

          $(".movies").append(card);
          def.resolve();
        });
      },
      error: function (data) {

      }
    });
    return def.promise();
  }

  function B() {
    var def = $.Deferred();
    $.ajax({
      type: 'GET',
      url: "https://rickandmortyapi.com/api/episode",
      dataType: "json",
      success: function (data) {
        var results = data.results;

        $.map(results, function (v, i) {
          $("#" + v.id).find(".card-epi").text(v.name)
        });
        def.resolve();
      },
      error: function (data) {
        console.log("errors in B()", data);
      }
    });
    return def.promise();
  }

  A().then(function() {
    console.log('A executed');
    return B();
  }).then(function() {
    console.lob('B executed');
  });
});

1 Comment

good one , I didn't know there is Deferred() in jQuery. Will keep it in mind :)
1
function A(){
        return $.ajax({
            type: 'GET',
            url: "https://rickandmortyapi.com/api/character/",
            dataType: "json",
            success: function (data) {
                var results = data.results;

                ...
                ...
                ... 
            },
            error: function(data){
                ...
            }
        });
    }

function B(){
        $.ajax({
                ... 
                ... 
                ... 
            },
            error: function(data){
                ... 
            }
        });
    }

A().then(B); //Chained...

3 Comments

nope, then takes a function as input and runs it itself.. so in this case passing only B would execute it as well.. This is useful when you dont have to pass any additional parameters, it can also accept data passed from resolver of A suppose A resolves to true then B would have true as first parameter value.
I believe my answer is better then other answers in this question. as I have better and shorter answer ;)
Hi M, thanks for your explanation. Your answer is same to 31piy. but he was the 1st to reply my question. :)
0

just call B() in the success Handler of A()

1 Comment

sorry, I didn't state my question clear. In fact, in side the $.map(results, function (v, i) { var card = .... I have another ajax call. Due to the async feature of javascript ajax call, I cannot put B() in side success Handler of A().

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.