It's really hard to write an answer with so little concrete information, but I will try.
I think what you need are promises, as they allow you to chain multiple asynchronous actions. As soon as there is an error, the chain will break, causing an error handler (that you can optionally specify) to be called.
Let's define a function functionA
that loads the file a.json
:
function functionA () {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'a.json');
xhr.onload = function () { resolve(xhr.response); };
xhr.onerror = function () { reject('Could not load a.json'); };
});
}
Use this function like this:
functionA().then(function (response) {
// this function is called as soon as the contents of the file are loaded
// response contains the contents of the file
}).catch(function (errorMessage) {
// this function is called whenever an error occurs
// errorMessage contains the error message
});
Let's say you define the functions functionB
and functionC
in a similar way to functionA
. You could then use it like this:
let contentsOfFileA = '';
let contentsOfFileB = '';
let contentsOfFileC = '';
functionA()
.then(fileA => {
contentsOfFileA = fileA;
return functionB();
}).then(fileB => {
contentsOfFileB = fileB;
return functionC();
}).then(fileC => {
contentsOfFileC = fileC;
// now, all files are loaded and you can use the variables
// contentsOfFileA, contentsOfFileB and contentsOfFileC
}).catch(error => console.log('An error occurred:', error));
The snippet above contains very redundant code. Using the Promise.all
, you can shorten it:
Promise.all(functionA(), functionB(), functionC())
.then([fileA, fileB, fileC] => {
// do something with the three files' contents
}).catch(error => console.log('An error occurred:', error));
Of course, what functionA
, functionB
and functionC
are doing is very trivial. To load a JSON file, you can also use the fetch API:
Promise.all(['a.json', 'b.json', 'c.json'].map(file => fetch(file)))
.then(responses => Promise.all(responses.map(r => r.json())))
.then(([fileA, fileB, fileC]) => {
// do something with the three files' contents
}).catch(error => console.log('An error occurred:', error));