我正在使用请求库。我有一个 URL 数组(var 资源),我想用这些 URL 的文本内容填充它们。
我的代码如下所示:
var resources = [<URL_1>, <URL_2>, <URL_3>, ...];
var resourcesText = resourceToText(resources);
function resourcesToText(resources) {
var text = [];
for (var i in resources) {
request(resources[i], fetch);
}
function fetch(error, response, body) {
if (!error) {
text.push(body);
} else {
console.log('Sorry. I couldn\'t parse that resource. ' + error);
}
}
return text;
};
问题在于,resourceToText() 在 fetch() 有时间填充数组之前就返回了该数组。因此,resourcesText 最终为空。我认为高阶函数旨在处理此类问题,但我无法理解处理回调的方法。
解决这个问题的最佳方法是什么?
最佳答案
通过以下方式从 resourcesToText
中创建一个异步函数:
使用额外的回调:
function resourcesToText(resources, callback) {
var text = [],
requestCount = resources.length;
for (var i in resources) {
request(resources[i], fetch);
}
function fetch(error, response, body) {
if (!error) {
text.push(body);
} else {
console.log('Sorry. I couldn\'t parse that resource. ' + error);
}
requestCount--;
if(requestCount <= 0){
callback(text);
}
}
};
使用计数器 (requestCount
) 获取请求的所有结果后,使用结果文本
调用回调。
现在对 resourcesToText
的调用如下所示:
resourcesToText(resources, function(text){
...
});
使用延迟/ promise
除了使用回调之外,您还可以实现延迟/ promise 的概念。有很多库,例如 q ( https://github.com/kriskowal/q )
关于JavaScript:如何确保此函数仅返回完全填充的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31674092/