【问题标题】:Skip iteration if response is null in async.jquery如果 async.jquery 中的响应为空,则跳过迭代
【发布时间】:2018-06-09 15:16:11
【问题描述】:

我正在使用 asyncjs 加载 Google 图表,它工作正常,但有时我从中获取图表数据的 api 返回空值,它会停止加载更多图表。

这是我的代码

async.eachSeries($('.WeeklyGraph'), function(e, cb){
var ticker = $(e).data('coin');
// console.log(ticker);
$('#'+ticker+'loader').removeClass("hide-sideLoader");
$.getJSON('https://coincap.io/history/7day/'+ticker, function(data){
    // console.log(data);
var month = new Array();
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
    var CoinPrices = data['price'];
        $.each(CoinPrices, function(index, CoinObject){
            var date = new Date(CoinObject[0]);
            var day = date.getDate();
            var Month = date.getMonth();
            var hours = date.getHours()+ ":" + date.getMinutes();
            CoinObject[0] = day+" "+month[Month]+" "+hours;
        });  
        google.charts.load('current', {packages: ['corechart', 'line']});
        google.charts.setOnLoadCallback(function(){
        var data = new google.visualization.DataTable();
        data.addColumn('string', '');
        data.addColumn('number', '');
        data.addRows(CoinPrices);
        var options = {
            enableInteractivity: false,
           legend: {position: 'none'},
            hAxis: {
            title: '',
            baselineColor: 'none',
            ticks: [],
            gridlines: {color: 'none'}
        },
        vAxis: {
            title: '',
            baselineColor: 'none',
            ticks: [],
            gridlines: {color: 'none'}
        },
            colors: ['#74b42a', '#74b42a']
        };
        var chartID = ticker+'chart_div';
        var chart = new google.visualization.LineChart(document.getElementById(chartID));
        chart.draw(data, options);
        $('#'+ticker+'loader').addClass("hide-sideLoader");
        // $("#chartContent"+coinID).removeClass("hide-chart");
        });

    cb();
});

});

现在我得到响应的data 变量,有时它返回 null 并且进一步的迭代停止。

我已经尝试过设置

 if (data == null)
     return;

   if (data == null)
     return true;

但它会停止所有进一步的迭代。

【问题讨论】:

    标签: javascript jquery asynchronous async.js google-visualization


    【解决方案1】:

    您应该使用callback 函数来进行下一次迭代。即

    if(data == null){
         cb(); //in your case, cb is your callback function
     }
    

    【讨论】:

    • 不应该从当前的回调迭代中返回吗? cb(); return; 编辑:我在 OP 的代码中看到它不会有太大区别,但使用 return; 会更加优化和明确
    • 他已经提到return; 对他不起作用,这就是为什么我建议只调用他的cb 函数
    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2014-12-12
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    相关资源
    最近更新 更多