我在这里使用此函数两次来加载csv数据:http://papaparse.com/
Papa.parse("http://example.com/file.csv", {
download: true,
complete: function(results) {
console.log(results);
}
});
当两个文件都准备就绪时,我想执行另一个函数,该函数取决于两者的结果。我正在用标记设计地图。
我想到了JavaScript Promises。如果你有2个csv文件/网址,有人可以帮我看看会是什么样子吗?
目前我已激活以下库:
Jquery 3.2.1
Papa Parse 4
最后,我知道:How to use Promises with PapaParse?但我无法弄清楚将代码放在哪里可以使用2个或更多文件。
您可以使用以下代码,如果必须在较旧的浏览器中运行,并且没有本机承诺或箭头功能,则需要使用babel和polyfill。
如果你有一系列网址,你可以这样做:
urls = ['path1.csv','path2.csv']
Promise.all(//pass array of promises to Promise.all
urls//you have an array of urls
.map(//map urls to promises created with parse
url=>
new Promise(//create one promise
(resolve,reject)=>
Papa.parse.parse(
url,
{
download: true,
complete:resolve,//resolve the promise when complete
error:reject//reject the promise if there is an error
}
)
)
)
)
.then(
function (results) {
console.log(results[0]) // log result from file 1
console.log(results[1]) // log result from file 2
}
)
.catch(//log the error
err=>console.warn("Something went wrong:",err)
)