d3.js / queue.js:如何跳过queue.js中的错误

时间:2015-03-07 10:07:11

标签: d3.js queue.js

我正在使用last.fm APIqueue.js动态合并用户的每周曲目列表和曲目信息数据集。当我对某首歌的AJAX调用返回错误时,我遇到了问题。我的主要问题是,如何跳过这些错误?具体来说,如何更改Mike Bostock's taskThatSometimesFails function以继续进行下一次d3.json来电?

这是我的原始代码:

d3.json(top, function(json) {

    weeklyChart = json.weeklytrackchart.track;

    var q = queue()
        .defer(d3.json, top);

    weeklyChart.forEach(function(d) { 
            tracks = 'http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=...&artist='+ d.artist['#text'] + '&track=' + d.name + '&format=json';             
            q.defer(d3.json, tracks);
            });

    q.awaitAll(function(error) {    
            if (error) throw error;
            console.log(arguments);

此处Mike Bostock's suggested way of skipping over error/null responses

    queue(1)
        .defer(ignoreError, taskThatSometimesFails)
        .defer(ignoreError, taskThatSometimesFails)
        .awaitAll(function(error, results) {
          if (error) throw error; // never happens
          console.log(results); // e.g., [0.23068457026965916, undefined]
        });

    function ignoreError(task, callback) {
      task(function(error, result) {
        return callback(null, result); // ignore error
      });
    }

    function taskThatSometimesFails(callback) {
      setTimeout(function() {
        var x = Math.random();
        if (x > .5) return callback(new Error("failed"));
        callback(null, x);
      }, 250);
    }

我不知道node.js,我对callbacksetTimeout的工作方式感到很困惑。我试着根据我的情况调整迈克的代码,但是我对taskThatSometimesFails(我认为神奇的地方)的处理方式感到困惑。这是我目前的,糟糕的改编:

d3.json(top, function(json) {

    weeklyChart = json.weeklytrackchart.track;

    var q = queue()
        .defer(d3.json, top);

    weeklyChart.forEach(function(d) { 
            tracks = 'http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=...&artist='+ d.artist['#text'] + '&track=' + d.name + '&format=json';             
            q.defer(d3.json, tracks);
            });

    function ignoreError(task, callback) {
        task(function(error, result) {
            return callback(null, result);
        });
    }

    function taskThatSometimesFails(callback) {
        setTimeout(function() {
            if (error) return callback(new Error("failed"));
            return callback(null, tracks); //or maybe return d3.json(tracks)?
        }, 1000);
    }


    q.awaitAll(function(error) {    
            if (error) throw error;

目前,任何空响应仍然会破坏整个队列。任何帮助,一如既往,赞赏。谢谢,伙计们。

0 个答案:

没有答案