我正在寫一個應用程序在JavaScript中,我向服務器發出CORS請求以獲取數據數組。從異步調用返回一個數組,然後額外的異步調用數組中的每個元素
然後,對於數組中的每個項目,我需要進行另一個CORS調用以獲取有關該元素的其他信息。
我本來以爲從我CORS要求像我可以返回值:
data = getData(param);
但很顯然,你不能混用同步和異步代碼。
完成此操作的最佳方法是什麼?
我正在寫一個應用程序在JavaScript中,我向服務器發出CORS請求以獲取數據數組。從異步調用返回一個數組,然後額外的異步調用數組中的每個元素
然後,對於數組中的每個項目,我需要進行另一個CORS調用以獲取有關該元素的其他信息。
我本來以爲從我CORS要求像我可以返回值:
data = getData(param);
但很顯然,你不能混用同步和異步代碼。
完成此操作的最佳方法是什麼?
承諾。您可以按照您的要求使用它們,並使用setTimeout
來模仿AJAX請求。
getData
返回新的承諾。在這種情況下,如果調用沒有參數的函數,則在第二次(第一次請求)之後發回一個數組。如果一個參數被傳入函數100
在解析之前被添加到參數 - 稍後的請求。
function getData(param) {
return new Promise(function(resolve, reject) {
if (param) {
setTimeout(() => resolve(param + 100), 500);
} else {
setTimeout(() => resolve([1, 2, 3, 4, 5]), 1000)
}
});
}
呼叫getData
沒有PARAM和[1, 2, 3, 4, 5]
返回。 then
我們映射數組元素並返回新的對他們每個人的承諾。 then
我們使用Promise.all
來解決這些承諾,then
我們輸出最終的數組[101, 102, 103, 104, 105]
。
getData()
.then((arr) => arr.map(el => getData(el)))
.then(arr => Promise.all(arr))
.then(arr => console.log(arr));
所以你可以看到,你可以運行一個AJAX請求,然後根據直到所有請求已作出所返回的值的結果運行更多。
您可以使用async.series。結帳https://github.com/caolan/async。非常好的庫來解決這樣的問題 - 異步處理數組數據(我的最愛)。
或者
您可以使用從https://www.promisejs.org/
或者有回調玩JS承諾......像下面
注:以下功能指示功能只是爲了展示如何您可以解決問題,因爲您沒有共享任何代碼。相應地更改它們。也可能會出現語法/拼寫錯誤,因爲代碼直接寫入此處。
function ajaxRequester(method,uri, data, onSuccess, onError){ // you can make this function as per requirement.
$.ajax({
type: method,
url: uri,
data: data
success: function(response){
onSuccess(response);
}
});
}
function yourFunction(){
ajaxRequester('GET',urlOf1stRequest,dataToSend,function(resp){
// assuming resp is the array received from server. we'll start with 0th element
processArray(0,resp, function(){
// do your final stuff
});
});
}
function processArray(index, arr, onComplete){
if(index < arr.lenght){
var objToProcess = arr[index]; // get your data to process
ajaxRequester(yourMethod,obj.url, obj.data, function(resp){
// do work with your response variable resp
processArray(++index, arr); // process next element of array after completion of current
});
} else {
onComplete(); // all elements are processed call final callback
}
}
您能否展示一個更完整的代碼示例,演示如何嘗試「混合同步和異步代碼」? –