我有以下代碼從MySQL數據庫獲取信息。 DB包括幾個表格,其中包括具有channelId字段的Activity
表格,具有userId字段的Channel
表格和具有userName字段的User
表格。 功能getAllProjectACtivities(user,project)
返回一個Activity
對象數組的承諾,每個對象都包含所有Activity
表字段。 函數findChannel(channelId)
返回單個對象的承諾,包括所有的Channel
表字段。 功能findUser(userId)
返回單個User
對象的承諾,包括所有User
表字段。 所有3個函數都向數據庫隱藏了一個JSON Ajax請求,並且已經過測試以獨立運行。JavaScript Promise.all代碼不能按預期工作
我在這裏要做的是獲取活動列表,爲他們每個人獲取頻道,爲每個頻道獲取用戶。然後我建立一個由2個活動字段和一個用戶字段組成的活動表。
爲此,我需要一個3階段的數據庫訪問,產生對象數組。下面是代碼:
$(document).ready(function(){
var projNum=1;
var userNum=1;
var globalActivityList; //this global array will store data from the beginning of the promise chain to be used at the end of the chain
$('#tableContainer').append('<table border="0" style="background-color: lightblue;"></table>');
var table = $('#tableContainer').children();
//here goes:
getUserProjectActivities(userNum,projNum)
.then(function (activityList){
table.append("<tr><th>Number</th><th>Description</th><th>Employee</th></tr>");
globalActivityList=activityList;
return Promise.all(activityList.map(function(activity){
//alert(activity.activityChannelId);//******** shows the right stuff
findChannel(activity.activityChannelId);
}));
})
.then(function (channelList){
alert (channelList.length);//******* gives the right size
alert (channelList);//******** u-oh, this shows ,,,,,,,,,,,, - the array is empty.<<<<<<<<<<<<<<<Problem
return Promise.all(channelList.map(function(channel){
findUser(channel.channelEmployeeId);
}));
})
.then(function(userList){
for (var i=0; i<userList.length; i++){
var tableString="<tr>";
tableString+="<td>"+globalActivityList[i].activitityId+"</td>";
tableString+="<td>"+globalActivityList[i].activitityDescription+"</td>";
tableString+="<td>"+userList[i].userName+"</td>";
tableString+="</tr>";
table.append(tableString);
}
})
});
接下來會發生什麼,然後獲取一個沒有信息的數組,然後所有後續代碼都失敗。 有什麼想法?謝謝。
享受你的銀色徽章:) – 2014-10-11 15:57:55
@BenjaminGruenbaum:哦,謝謝 - 我有點晚了[聚會](http: //堆棧溢出。com/help/badges/4124/promise):-) – Bergi 2014-10-11 16:04:26
如果標籤我很在意假期,直到第21天:) – 2014-10-11 16:05:39