I am working on a p5.js project that loads some configuration options from a JSON file. I am preloading the config file in p5.js's preload()
function, like so:
let config = {};
function preload() {
config = loadJSON("data/config.json");
}
Part of the config JSON file contains some song
objects that each have a filename
property that is another JSON file I would like to preload:
"songs": [
{
"title": "Song One",
"filename": "01.json"
},
...
]
I cannot access the config file data before p5.js's setup()
function (as I cannot guarantee the config file has been completely read until then), by which time I can no longer preload the song JSON files.
I'm trying to figure out if there's any way around this.
EDIT: Thanks to George's answer below, I have it working as below. The following all runs before entering p5.js's setup()
function, which is exaclty what I was after:
let config = {};
function preload() {
config = loadJSON("config.json", configLoaded);
}
function configLoaded(_config) {
let songs_length = _config.album.songs.length;
for (let i = 0; i < songs_length; i++) {
loadJSON("data/" + _config.album.songs[i].filename, songLoaded);
}
}
function songLoaded(_song) {
console.log(_song);
}