我是新來鏈接JavaScript承諾。我閱讀了關於上述錯誤的所有答案。增加了很多返回,但仍然不明白爲什麼它返回undefined。Uncaught TypeError:無法讀取鏈接3 getJson調用時未定義的屬性'then'
我有3個getJson調用(用戶,標誌和流)。來自所有三個數據都在thisNameInfo數組中進行收集,並用於構建html。
在其中一個prevous版本中,所有的陳述都鏈接在一個signle行中。這並沒有產生錯誤,但是在執行getJson調用之前構建了html。看完這個線程how to chain then functions我加了3個調用例程(callUser,callLogo和callStream)。
它通過第一個呼叫用戶,並給我無法讀取屬性'then'的未定義的'then'在callLogo之後。在代碼中使用``````````````````強調錯誤點。
感謝您的幫助。
如果你有建議如何更好地將數據從getJson調用傳遞給構建html的函數,我很樂意聽到它。
這裏是我的代碼:
var allStreamers = ["freecodecamp", "animeexpo", "brunofin"];
// build html for one stereamer
var buildStreamerHtml = function(thisNameInfo){
//build html using thisNameInfo
... some code goes here
$("#display").append(html);
};
// get user
var user = function(name, thisNameInfo){
// return promise or "then" will return undefined!!!
return $.getJSON(
"https://wind-bow.glitch.me/twitch-api/users/" + name,
function(data) {
// if user does not exist data.error if 404 and data.message exist
if (data.message) {
thisNameInfo.userExist = "no";
thisNameInfo.title = data.message;
thisNameInfo.url = "#";
thisNameInfo.logo = "";
} else{
thisNameInfo.userExist = "yes";
}
});
};
// get logo, title and url
var logo = function(name, thisNameInfo){
if (thisNameInfo.userExist === "yes"){
// get logo and title with link to url
// return promise or "then" will return undefined!!!
return $.getJSON("https://wind-bow.glitch.me/twitch-api/channels/" + name,
function(dataChannel) {
thisNameInfo.url = dataChannel.url;
thisNameInfo.title = dataChannel.display_name;
thisNameLogo.logo = dataChannel.logo;
});
}
};
// get stream title and number of watchers
var stream = function(name, thisNameInfo){
if (thisNameInfo.userExist === "yes"){
// return promise or "then" will return undefined!!!
return $.getJSON("https://wind-bow.glitch.me/twitch-api/streams/" + name,
function(dataStreams) {
if (dataStreams.stream) {
thisNameLogo.status = "Online";
thisNameLogo.streamTitle = dataStreams.stream.channel.status;
thisNameLogo.viewers = dataStreams.stream.viewers;
} else {
thisNameLogo.status = "Offline";
}
});
}
};
var callUser = function(name, thisNameInfo){
return user(name, thisNameInfo).then(callLogo(name, thisNameInfo));
};
var callLogo = function(name, thisNameInfo){
return logo(name, thisNameInfo).then(callStream(name, thisNameInfo));
}; ``````````````````````````````````````
var callStream = function(name, thisNameInfo){
return stream(name, thisNameInfo);
};
// link together all asinhronious calls for one streamer
var getStreamerInfo = function(name){
"use strict";
// this variable builds up by assinhronious calls
// then its value is usedd by buildStreamerHtml
console.log("getStreamerInfo name: " + name);
var thisNameInfo = {};
callUser(name, thisNameInfo).then(buildStreamerHtml(thisNameInfo));
};
// loop through all streamers and display them
allStreamers.forEach(getStreamerInfo);
第二承諾後,取消定義點callLogo
謝謝jayjaycross。這解決了它。 – Ivana