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/