我正在尝试处理以下问题。
在下面的代码中,我试图从内部then
函数中获取结果。我希望let online
函数将返回onlineResult.stream
。但是,它返回:
或null
当它为空时。
var baseUrl = "https://wind-bow.gomix.me/twitch-api";
var channels = [
"ESL_SC2",
"OgamingSC2",
"cretetion",
"freecodecamp",
"storbeck",
"habathcx",
"RobotCaleb",
"noobs2ninjas"
];
function fetchChannels(channels) {
var listItems = [];
if (Array.isArray(channels)) {
const results = channels.map(channel =>
$.getJSON(`${baseUrl}/channels/${channel}?callback=?`)
);
Promise.all(results).then(values => {
values.forEach(val => {
let online = $.getJSON(`${baseUrl}/streams/${val.name}?callback=?`)
.then(onlineResult => {
return onlineResult.stream;
})
console.log(online);
listItems.push([val.name, val.logo]);
});
});
}
}
fetchChannels(channels);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 0 :(得分:0)
您可能要做的是在第一个频道请求中添加then()
,并在到达时立即获取与该频道相关联的流
类似的东西:
var baseUrl = "https://wind-bow.gomix.me/twitch-api";
var channels = ["ESL_SC2", "OgamingSC2"];
function fetchChannels(channels) {
if (!Array.isArray(channels)) {
return Promise.reject('No channels array')
} else {
const channelPromises = channels.map(channel =>
$.getJSON(`${baseUrl}/channels/${channel}?callback=?`)
.then(fetchStream)
);
return Promise.all(channelPromises)
}
function fetchStream(channelResult) {
return $.getJSON(`${baseUrl}/streams/${channelResult.name}?callback=?`)
.then(streamResult => {
return streamResult.stream;
}).then(stream => {
// adding the result of stream request as property of channel request ... adapt as needed
channelResult.stream = stream;
return channelResult
})
}
}
fetchChannels(channels)
.then(res => console.log(res))// array of channel requests, each has a `"stream"` property
.catch(err => console.log(err))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
&#13;