用这么少的具体信息写一个答案真的很难,但我会努力的。
我认为您需要的是promises,因为它们允许您链接多个异步操作。一旦出现错误,链就会中断,从而调用错误处理程序(您可以选择指定)。
让我们定义一个函数functionA 来加载文件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'); };
});
}
像这样使用这个函数:
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
});
假设您以与functionA 类似的方式定义函数functionB 和functionC。然后你可以像这样使用它:
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));
上面的 sn-p 包含非常冗余的代码。使用Promise.all,您可以缩短它:
Promise.all(functionA(), functionB(), functionC())
.then([fileA, fileB, fileC] => {
// do something with the three files' contents
}).catch(error => console.log('An error occurred:', error));
当然,functionA、functionB 和 functionC 所做的事情非常琐碎。要加载 JSON 文件,您还可以使用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));