[英]How to update value after Ajax call synchroniously
我正在從我的節點(快速)后端服務器獲取數據以對前端做出反應。 但是當我嘗試訪問數組索引值時,我得到的輸出是未定義的。 我肯定在這里做錯了什么。 感謝有人可以幫助我。
這是我的服務器端代碼:
const companyDetails = [];
companies.forEach((company) => {
companyDetails.push(company);
});
app.get("/api/companies", (req, res) => {
res.json(companyDetails)
});
這是我的客戶端代碼:
let arr = [];
function fetchComNames() {
axios.get('/api/companies').then(res => {
for(let i=0; i<=4; i++) {
arr.push(res.data[i].name)
}
})
}
fetchComNames();
console.log(arr[0]); //undefined
但是當我console.log(arr);
它打印出數組。 我只是無法分別訪問每個索引值。
這里的問題是axios
調用是一個async
調用,您的代碼axios
是sync
因此當您執行此代碼時, javascript
執行sync
代碼,然后執行async
代碼,因此在這種情況下,代碼行onsole.log(arr[0]);
在響應來自服務器之前執行
添加到以下答案中, fetchComNames
會在您使用 API 調用時異步更新arr
。 您在數據更新之前訪問數據,這就是為什么要獲取undefined
。
你可以試試這個。
const fetchComNames = async () => {
try {
const response = await axios.get('/api/companies')
const array = response.data.map(c => c.name)
OR
const array = []
for (let i = 0; i<= 4; i++) {
array.push(response.data[i].name)
}
console.log(array[0])
} catch(err) {
console.error(err)
}
}
fetchComNames()
API 調用是異步的,因此您要在數組中包含其值之前訪問該數組。 嘗試將您的封閉函數標記為 async 並等待 axios get 以便強制調用同步。
let arr = [];
async function fetchComNames() {
const fetched = await axios.get('/api/companies');
for(let i=0; i<=4; i++) {
arr.push(fetched.data[i].name)
}
}
fetchComNames();
console.log(arr[0])
(async () => {
const arr = [];
// Marking this function as async function so that
// we can use await to wait until result returning
// before further executing code below
async function fetchComNames() {
// I don't have access to you API
// I resolve data after 1 second to simulate Ajax call here
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({
data: [{
name: "1"
}, {
name: "2"
}, {
name: "3"
}, {
name: "4"
}]
});
}, 1000);
}).then(res => {
return res.data.map(each => each.name)
});
}
// You are calling Ajax call via Axios, which is a Promise.
// It is executed asyncrhoniously.
// If you need to use result from this call,
// you need to wait until result returning from async call.
// You can achieve it with await.
// Update existing array
arr.push(...(await fetchComNames()));
// After await, arr should contain result you expected.
console.log(arr[0]);
// There reason why your version is not working
// is because you are accessing the first cell of arr
// wihich is still empty as the Axios is still running
// and you are not waiting until it returns result.
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.