Queue.js预加载图像永远等待? (Callbak) [英] Queue.js to preload images is waiting forever? (Callbak)
问题描述
我使用 mbostock queue.js脚本加载多个json文件,通过执行类似的操作:
I'm using mbostock queue.js script to load several json files, by doing something like that:
var q = queue()
.defer(d3.json, "world-110m.json")
.defer(d3.tsv, "world-country-names.tsv")
.await(ready);
其中ready是在加载everythin时执行的函数。
where ready is the function to execute when everythin is loaded.
我想通过添加一个defer来预加载一个图像。这可能吗?我已经尝试了几种方法,但它不工作。
I would like to preload an image by adding a defer. Is this possible? I have tried it several ways, but it doesn't work.
我假设一个函数必须创建,但我不能使它异步,队列总是等待...
I suppose that a function must be created, but I can't make it asynchronous, and the queue keeps waiting forever...
推荐答案
这里是queue.js期望从回调:
Here is what queue.js is expecting from the callbacks:
回调跟随节点。 js约定,其中第一个参数是可选错误对象,第二个参数是任务的结果。
The callbacks follow the Node.js convention where the first argument is an optional error object and the second argument is the result of the task.
因此,您的代码的简单版本可能如下所示:
Thus a simple version of your code might look like this:
var loadImage = function(src, cb) {
var img = new Image();
img.src = src;
img.onload = function(){ cb(null, img); };
img.onerror = function(){ cb('IMAGE ERROR', null); };
};
queue()
.defer(d3.json, "data/flare.json")
.defer(d3.csv, "data/test.csv")
.defer(loadImage, "img/test.png")
.await( function(error, jsondata, csvdata, imagedata) {
if (error) { console.log('error', error); }
else { console.log('success', jsondata, csvdata, imagedata) }
});
我不知道你想要返回的图片,上面的例子 cb(null,img)
我要返回整个对象。
I'm not sure what (if anything) you wanted to return about the image, but in the above example cb(null, img)
I'm returning the whole object.
这篇关于Queue.js预加载图像永远等待? (Callbak)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!