I'd like to make an API call that prints out the values retrieved from 2 helper API calls.
See:
function api_call() {
$.ajax({
url: "...",
success: function (objects) {
for (var i = 0; i < objects.length; i++) {
var id_1 = api_helper1(objects[i].id_1);
var id_2 = api_helper2(objects[i].id_2);
console.log(id_1 + id_2);
}
}
});
}
function api_helper1(id_1) {
$.ajax({
url: "...",
success: function (value) {
return value;
}
});
}
function api_helper2(id_2) {
$.ajax({
url: "...",
success: function (value) {
return value;
}
});
}
The issue here is AJAX is async so api_helper1 and api_helper2 will run before console logs id_1 + id_2
. What is the cleanest way to accomplish this without having multiple AJAX calls inside each other's success function?
You can do this with Promises:
function api_call() {
return $.ajax({
url: "...",
});
}
function api_helper1(id_1) {
return $.ajax({
url: "..."
});
}
function api_helper2(id_2) {
return $.ajax({
url: "..."
});
}
api_call().done((objects)=>{
for (var i = 0; i < objects.length; i++) {
$.when(api_helper1(objects[i].id_1), api_helper2(objects[i].id_2)).then((id_1, id_2)=>console.log(id_1 + id_2));
}
})
This is how I would do it with Promises
$.ajax({
url: '/getTag.php',
type: 'POST',
dataType: 'html',
data: {tag:tag,docid:doc},
error:function(err){
reject(err)
},
complete:function(comp){
let objects = JSON.parse(comp.responseText);
for(var i = 0; i < objects.length; i++){
apicall1(objects[i].id_1).then((id_1)=>{
apicall2(objects[i].id_2).then((id_2)=>{
console.log(id_1 + id_2)
})
})
}
}
})
function apicall1(tag){
return new Promise((resolve, reject) => {
$.ajax({
url: '/getTag.php',
type: 'POST',
dataType: 'html',
data: {tag:tag},
error:function(err){
reject(err)
},
complete:function(comp){
let jsons = JSON.parse(comp.responseText);
resolve(jsons)
}
})
})
}
function apicall2(tag){
return new Promise((resolve, reject) => {
$.ajax({
url: '/getTag.php',
type: 'POST',
dataType: 'html',
data: {tag:tag},
error:function(err){
reject(err)
},
complete:function(comp){
let jsons = JSON.parse(comp.responseText);
resolve(jsons)
}
})
})
}
More info about how to use them https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise