![](/img/trans.png)
[英]Javascript - Trying to save the result of a function to an object. Object is null
[英]Async fetch data, aggregate the result to an object. Is the object locked by javascript by default?
假設我要從1000台服務器中獲取一些數據。 每個服務器返回相同的json結構。 虛擬示例:
{
logins: 5000,
clicks: 1000
}
假設我需要匯總每個服務器響應中的所有登錄信息。
我想在每個回調(= 1000次)中執行此操作,而不是查詢所有json然后執行總和。 基本示例:
var result = 0;
$http.get(url).then(function(response) {
result += response.data.logins;
});
解釋為什么需要鎖定的示例:
如果我的第一台服務器返回1000,則第二台服務器返回2000,第三台服務器返回3000;
假設由於某種原因,當第三個回調稱為我的諾言時,第二個還未完成。
如果沒有鎖定結果,則在第三個回調結束時可能等於4000,這是錯誤的(正確值為6000);
那你們覺得呢? 結果是否自動鎖定? 如果不是,是否很容易在js中創建鎖定模式?
感謝您的回答!
我更新了答案,因為問題已編輯:
如果發送許多ajax調用請求,則響應可能無法按順序進行,因此,如果需要該命令,則可以強制ajax調用同步運行( 如果使用Angular中的$ http則不能 )。
但是我永遠不會那樣做(我總是會使用異步),尤其是因為您要發送的請求數量...
如果您願意,可以執行類似的操作,只需在上一個成功回調中調用下一個端點:
$http.get(url).then(function(response) {
result += response.data.logins;
$http.get(url).then(function(response) {
result += response.data.logins;
/// ... (use a loop)
});
});
例:
const data = [ { isActive: "1", logins: 1000, clicks: 1000 }, { isActive: "1", logins: 2000, clicks: 1000 }, { isActive: "1", logins: 3000, clicks: 1000 }]; const callApi = (index, timeout) => { return new Promise((resolve, reject) => { setTimeout(() => resolve({data: data[index]}), timeout); }) }; let result = 0; let timeouts = [0, 3000, 0]; const callback = (resp, index) => { result += resp.data.logins; console.log(`Result now in callback ${index + 1}:`, result); if (index < timeouts.length - 1) { index++; callApi(index, timeouts[index]).then(resp => callback(resp, index)) } } callApi(0, timeouts[0]).then(resp => callback(resp, 0))
根據您要實現的目標,我將使用鍵在回調中跟蹤請求,即使您需要也可以使用服務器。
如果您只需要所有“登錄”計數器的總和,而無需訂購
const data = [ { isActive: "1", logins: 1000, clicks: 1000 }, { isActive: "1", logins: 2000, clicks: 1000 }, { isActive: "1", logins: 3000, clicks: 1000 }]; const callApi = (index, timeout) => { return new Promise((resolve, reject) => { setTimeout(() => resolve({data: data[index]}), timeout); }) }; let result = 0; [0, 3000, 0].forEach((timeout, index) => { callApi(index, timeout) .then(res => { result += res.data.logins console.log(`Result now in callback ${index + 1}:`, result) }) });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.