用這麼少的具體信息寫出答案真的很難,但我會嘗試。
我認爲您需要的是promises,因爲它們允許您鏈接多個異步操作。只要出現錯誤,鏈就會中斷,導致調用錯誤處理程序(您可以選擇指定)。
讓我們來定義加載文件a.json
功能functionA
:
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
});
比方說,你定義以類似的方式功能functionB
和functionC
到functionA
。然後,您可以使用這樣的:
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));
的片段上方包含非常冗餘代碼。使用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));
[在另一個函數完成後執行jquery函數]可能的重複(https://stackoverflow.com/questions/19674380/execute-jquery-function-after-another-function-completes) –
歡迎來到Stack Overflow!請參考[參考],環顧四周,並閱讀[幫助],尤其是[*我如何提出一個好問題?](/ help /如何問)代碼是1024字。嘗試通過徹底的研究,調試等來完成您所描述的任務。**如果您遇到問題,請使用代碼的[mcve]發表問題,說明您遇到什麼具體問題以及您擁有什麼做診斷/修復它,人們會很樂意提供幫助。 –