据我所知,我错误地使用了异步功能。感谢您向我提供有关closure inside loops的类似问题,但我仍然需要有人帮助将其应用于我的CheckChannelStatus
功能。
我想根据条件将status
channelInfo
更改为offline
。它在其中一个函数中输出正确的结果:
function (response) {
var data = response.data,
channelInfo = {};
scope.channels = [];
console.log(data);
if (data.status && data.status != 200) {
channelInfo = {
name: data.status,
display_name: data.error,
logo: "",
status: data.message,
url: "#"
}
} else {
channelInfo = {
name: data.name,
display_name: data.display_name,
logo: data.logo,
url: data.url
};
CheckChannelStatus(
channelInfo.name, http, q
).then(
function(status) {
channelInfo["status"] = status; //status = "offline"
}
);
}
scope.channels.push(channelInfo); //status = "offline"
}
但是,在另一个函数中,status
属性保持不变:
function(response) {
var follows = response.data.follows;
scope.channels = [];
for (var i = 0; i < follows.length; i++) {
var channelInfo = follows[i].channel;
if (follows[i].channel.status == null) {
channelInfo.status = "offline";
} else {
CheckChannelStatus(
channelInfo.name, http, q
).then(
function(status) {
channelInfo["status"] = status; //status = "offline"
}
);
}
console.log(channelInfo.status);
scope.channels.push(channelInfo); //status != "offline"
}
console.log(scope.channels);
}
我还尝试从status
中的对象中删除else
属性,就像它在第一个函数中一样,但它不起作用。
这些函数位于角度控制器内部,第一个是在开始时加载,而借调是通过ng-click和ng-enter加载的:
function TwitchStream($scope, $http, $q) {
$scope.findChannel = function() {
FindChannel($scope, $http, $q); //ng-click, ng-enter
}
$scope.fccFollows = function() {
FccFollows($scope, $http, $q);
}
$scope.fccFollows();
}