[英]JavaScript: How can I make sure that this function only returns the fully populated array?
I'm using the Request library. 我正在使用请求库。 I have an array of URLs (var resources) that I want to populate with the text content of those URLs.
我有一个URL(可变资源)数组,我想用这些URL的文本内容填充。
My code looks like this: 我的代码如下所示:
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;
};
The problem is that resourceToText() returns the array before fetch() has had time to populate it. 问题在于resourceToText()在fetch()有时间填充数组之前返回了该数组。 Thus, resourcesText ends up being empty.
因此,resourcesText最终为空。 I assume higher order functions are meant to deal with this kind of problem but I can't fathom a way to work the callback.
我认为高阶函数旨在解决此类问题,但是我无法理解一种处理回调的方法。
What's the best approach to this problem? 解决此问题的最佳方法是什么?
Make an asynchronous function out of resourcesToText
by: 通过以下方法,从
resourcesToText
一个异步函数:
Using an additional callback: 使用其他回调:
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);
}
}
};
Call the callback with your result text
after you you got all the results of your requests using a counter ( requestCount
). 使用计数器(
requestCount
)获得所有请求的结果后,使用结果text
调用回调。
Now the call to resourcesToText
looks like: 现在,对
resourcesToText
的调用如下所示:
resourcesToText(resources, function(text){
...
});
Using deferred/promises 使用延迟/承诺
Instead of using a callback, you could also implement the concept of deferred/promises. 除了使用回调,您还可以实现延迟/承诺的概念。 There are many libraries out there, such as q ( https://github.com/kriskowal/q )
有很多库,例如q( https://github.com/kriskowal/q )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.