问题描述
我需要对一个API进行2次调用,每个API都包含一些总数据,然后需要进行迭代。调用1获取两个jsonp对象:
I need to make 2 calls to an API which each contain some of the total data, that then needs to be iterated over. Call 1 gets two jsonp objects:
[{
"id": 17,
"name": "A",
"campaign_code": "CAP20481"
},{
"id": 18,
"name": "B",
"campaign_code": "CAP20481"
}]
呼叫2使用第一次通话时的ID得到一个整数。然后我需要相应的名称和整数。到目前为止,我有:
Call 2 uses the ID from the first call to get an integer. I then need the corresponding "name" and integer. So far I have:
function getStoreCounts() {
var campaignID = $("input[title='Campaign ID']").val();
var storeLists = $.ajax({
type: "GET",
dataType: "jsonp",
url: "/apiIndex?callback=?&campaign_code=" + campaignID.toString(),
}),
storeCount = storeLists.then(function(data) {
$.each(data,function(i,storeList){
$.extend(storeList,{stores:''});
var getCount = $.ajax({
type: "GET",
dataType: "jsonp",
url: "/apiStoreCount?callback=?&list_id=" + storeList.id.toString(),
});
getCount.done(function(count) {
storeList.stores = count;
});
});
return data;
});
storeCount.done(function(data) {
console.log(data);
$.each(data,function(i,tierCount){
console.log("Tier: "+tierCount.name);
console.log("Stores: "+tierCount.stores);
});
});
}
最后已完成
当我注销整个数据数组时,promise返回,我得到每个对象的商店值。但是,当我尝试迭代数组中的每个对象时,我错过了存储值。来自Chrome的附加输出。
At the final done
promise return when I log out the whole data array, I get the stores values for each object intact. But when I try to iterate over each object in the array I'm missing the stores value. Attached output from Chrome.
推荐答案
你需要等待所有内心的承诺才能解决。
You need to wait for all inner promises to resolve. $.when
storeCount = storeLists.then(function(data) {
// array of promises
var counting = $.map(data,function(storeList){
$.extend(storeList,{stores:''});
var getCount = $.ajax({
type: "GET",
dataType: "jsonp",
url: "/apiStoreCount?callback=?&list_id=" + storeList.id.toString(),
});
return getCount.then(function(count) {
storeList.stores = count;
});
});
// wait for all
return $.when.apply($, counting).then(function() {
return data; //return modified data
})
});
关于命名对话的附注。您的函数名为 getStoreCounts
,但返回 undefined
。让它返回最终的承诺。
And a side note on naming convetion. Your function was named getStoreCounts
but returns undefined
. Let it return the final promise.
function gettingStoreCounts() {
var campaignID = $("input[title='Campaign ID']").val();
var storeLists = $.ajax({...}),
return storeLists.then(...);
}
并在结算方使用结果
gettingStoreCounts().then(/*log, whatever*/)
这篇关于使用promise为$ .ajax()回调添加其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!