I'm using this function here twice to load csv data: http://papaparse.com/
Papa.parse("http://example.com/file.csv", {
download: true,
complete: function(results) {
console.log(results);
}
});
When both files are ready I want to execute another function that depends on the results from both. I'm styling a map with markers.
I thought about JavaScript Promises. Can someone give me a hand on how that would look like if you have, say, 2 csv files/urls?
Currently I have the following libraries activated:
Jquery 3.2.1
Papa Parse 4
Lastly, I'm aware of: How to use Promises with PapaParse? But I can't figure out where to put the code for it to work with 2 or more files.
You could use the following code, if this has to run in browsers that are older and don't have native promises or arrow functions you need to use babel and polyfills.
If you have an array of urls you can do this:
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)
)