我想进行API调用,打印出从2个辅助API调用中检索到的值。
请参阅:
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;
}
});
}
这里的问题是AJAX是异步的,因此api_helper1和api_helper2将在控制台日志id_1 + id_2
之前运行。如果没有在彼此的成功函数中进行多次AJAX调用,最简单的方法是什么?
答案 0 :(得分:2)
你可以用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));
}
})
答案 1 :(得分:0)
这就是我用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)
}
})
})
}
有关如何使用它们的更多信息 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise