我遇到了一些似乎运行不正常的异步函数的问题。下面的脚本在少量元素上触发 forEach
,并通过使用原始元素 innerHTML
中的用户 ID 向 API 执行 AJAX 请求以获取用户名,并更新文本。
问题出在 users
对象周围,我想在其中存储以前获取的用户名,并绕过为同一用户执行后续 AJAX 调用的需要。我曾尝试使 forEach
回调异步并等待它,以及 window.onload
,但脚本似乎总是触发所有 AJAX 调用,而不是像我预期的那样等待。
// The object that stores user names that are fetched from API
const users = {};
const getusername = async (userId) => {
// Return the saved user name if it is stored already
if (users[userId]) {
return users[userId];
}
// Calls the API to get the name of the user
const response = await fetch(
`/user/${userId}/`,);
const username = await response.text();
// Store the user name to prevent duplicate calls
users[userId] = username;
return username;
};
const convertNameNode = async (nameNode) => {
const userId = nameNode.innerHTML;
const username = await getusername(userId);
// Replace the text in the DOM,e.g. from 1 to 'Steve'
nameNode.innerHTML = username;
};
// On load,trigger conversion of user IDs to user names
window.onload = () => {
document.querySelectorAll('.userId').forEach(node => {
convertNameNode(node);
});
};