使用迭代数组的JS回调不起作用

时间:2017-03-25 12:36:22

标签: javascript callback

我遇到了这个JS脚本的问题,因为好的Mr.Async不喜欢我。

即使tocsv函数假设等待csvdata的回调,也会在回调之前创建csv并且我得到一个空文件。

我非常感谢您帮助理解如何解决此问题

tocsv(sites,createcsv); 

// ITEREATE OVER FILE SITES.JS
function tocsv(urls, callback) {
	for (var i = 0; i < 3; i++) {
		var theurl = urls[i];

		getData(theurl, function(the_page_title) {
			csvdata.push([the_page_title]);
		});
	};
	callback(csvdata);
};

// Get title from url
function getData(url, callback) {
	csvdata = [];
	
	$.get(url, function(data){

			$("title", data).each(function() {
		  		
		  		the_page_title = $(this).text();
      });
	
		  callback(the_page_title);
    });
};
	
function createcsv(thedata) {
	var data = thedata;
	console.log(data);
	var csvContent = "data:text/csv;charset=utf-8,";
	data.forEach(function(infoArray, index){

	   dataString = infoArray.join(",");
	   csvContent += index < data.length ? dataString+ "\n" : dataString;

	}); 

	var encodedUri = encodeURI(csvContent);
	var link = document.createElement("a");
	link.setAttribute("href", encodedUri);
	link.setAttribute("download", "my_data.csv");
	document.body.appendChild(link); // Required for FF

	link.click(); // This will download the data file named "my_data.csv".	
}

1 个答案:

答案 0 :(得分:0)

试试这个

var csvdata = [];
tocsv(sites, createcsv);

// ITEREATE OVER FILE SITES.JS
function tocsv(urls, callback) {
    var count = 0
    for (var i = 0; i < 3; i++) {
        var theurl = urls[i];

        getData(theurl, function(the_page_title) {
            count++;
            csvdata.push([the_page_title]);
            if(count == 3) {
                callback(csvdata);
            }
        });
    };
};

// Get title from url
function getData(url, callback) {

    $.get(url, function(data) {

        $("title", data).each(function() {

            the_page_title = $(this).text();
        });

        callback(the_page_title);
    });
};

function createcsv(thedata) {
    var data = thedata;
    console.log(data);
    var csvContent = "data:text/csv;charset=utf-8,";
    data.forEach(function(infoArray, index) {

        dataString = infoArray.join(",");
        csvContent += index < data.length ? dataString + "\n" : dataString;

    });

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my_data.csv");
    document.body.appendChild(link); // Required for FF

    link.click(); // This will download the data file named "my_data.csv".  
}