我正在尝试创建一个查看器,它使用 twitch.tv API 来检查 twitch 流媒体数组,然后发布哪些用户当前在线以及他们正在流式传输的内容。我在弄清楚如何使用回调的异步性质时遇到了一些严重的问题。
我想为数组中的每个 twitch 用户循环一次 api 调用。在它们全部返回后,我希望能够对它们进行排序并按特定条件的顺序列出它们。
经过大量研究,我尝试使用 promise 来做到这一点。但是我仍然无法弄清楚这一点。
我用过这个问题:How can I wait for set of asynchronous callback functions?这个问题:How do I return the response from an asynchronous call?作为指导方针,但显然我仍然缺少一些重要的东西。我已经发布了我的代码的相关部分。我将不胜感激任何帮助/插入我所缺少的正确方向。
$(document).ready(function() {
var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff","ESL_SC2", "brunofin"];
var test = [];
function getData(){
var promises = [];
for (var i = 0; i < channels.length; i++) {
promises.push($.getJSON('https://api.twitch.tv/kraken/streams/'+channels[i]+'?callback=?', function(data) {}));
}
$.when.apply($, promises).then(function() {
// returned data is in arguments[0][0], arguments[1][0], ... arguments[9][0]
// you can process it here
for(var j=0; j<promises.length; j++){
//console.log(promises[j].responseJSON);
test.push(promises[j]);
}
}, function() {
// error occurred
conole.log("get data error");
});
}
getData();
console.log("do I have data?: ");
for(var j=0; j<test.length; j++){
console.log(test[j].responseJSON); //This is empty and where I need the data!
}
});
最佳答案
在代码中,您调用 getData()
,然后在下一行迭代 test
数组。这发生在事件循环的同一次传递中,因此您不会给您的 Promise 任何实际运行其逻辑并解决任何问题的机会。逐行执行是同步的,中间不能执行任何操作。
解决方案是从 getData
函数返回一个 Promise 并等待它解析。
由于您正在使用 Promises,因此您也不需要对 $getJSON
函数进行任何回调。
$(document).ready(function() {
var channels = [
"freecodecamp", "storbeck", "terakilobyte", "habathcx",
"RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff",
"ESL_SC2", "brunofin"
];
var test = [];
function getData() {
var promises = [];
for (var i = 0; i < channels.length; i++) {
promises.push(
$.getJSON(
'https://api.twitch.tv/kraken/streams/'+channels[i]+'?callback=?'
)
);
}
return $.when.apply($, promises).then(function() {
for(var j=0; j<promises.length; j++){
test.push(promises[j]);
}
});
}
getData().then(function() {
console.log("do I have data?: ");
for(var j=0; j<test.length; j++) {
console.log(test[j].responseJSON);
}
});
});
我还建议重构这段代码。这是一个有趣的问题,也是 JavaScript 中常见的事情,我想使用此示例演示如何使用 Promise 数组。
每个异步操作独立运行,您的直觉是正确的:您需要一些额外的工具将所有结果放在一起。
使用promise时,这个工具是Promise.all
。事实上,jQuery 的 $.when
是类似的,尽管我发现 Promise.all
由于其输入和返回类型而更容易使用。它也是标准 JavaScript,可在所有现代浏览器中使用。
Promise.all
可用于在多个单独的 Promise 解析时运行某些逻辑。形式上,Promise.all 接受一组 Promise 并返回一个 Promise,当所有输入 Promise 解析(或其中一个 Promise 拒绝)时,该 Promise 解析。它解析为单个 Promise 解析为的解析值数组。
由于 Promise.all
采用数组,因此它与 map
和 filter
等数组方法配合得很好。
function getStreams(channels) {
// Transform an array of channel names into an array of Promises
// representing the asynchronous action of getting the info
// about each channel.
const promises = channels.map(
channel => $.getJSON(
'https://api.twitch.tv/kraken/streams/'+channel+'?callback=?'
)
);
// Return a new promise which will resolve when *all* channels
// have been queried.
return Promise.all(promises);
}
const channels = [
"freecodecamp", "storbeck", "terakilobyte", "habathcx",
"RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff",
"ESL_SC2", "brunofin"
];
getStreams(channels).then(
// infos is an array of resolved data about the channels
infos => infos.forEach(
info => console.log(info)
)
);
关于javascript - 如何等到异步回调完成后再使用检索到的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36725786/