我想用回调包裹我的头绕过异步JS。在我的HTML中,我有一个按钮和一个div区域来显示文本。回调函数的输出没有被记录(JavaScript)
<button class="btn btn-default">Fetch User</button>
<hr>
<div></div>
我的JS如下:
const button = document.querySelector("button");
const div = document.querySelector("div");
const setText = (text) => {
div.textContent = text
}
const checkAuth = ca => {
setText('Checking Auth...')
setTimeout(() => {
ca(true);
}, 2000);
};
const fetchUser = fu => {
setText('Fetching User...')
setTimeout(() => {
fu ({ name: "PENNYWISE" }) ;
}, 2000);
};
const evilLaughter = el => {
setText('Red balloon drifting your way...')
setTimeout(() => {
el ({ laughter: "HA HA HA" }) ;
}, 2000);
};
button.addEventListener("click",() => {
checkAuth(isauth => {
if (isauth) {
fetchUser(user => {
setText(user.name);
evilLaughter(intro => {
setText(intro.laughter)
});
});
}
});
});
我期望在FOLL序列代码输出: 检查验证 - >获取用户 - >锱铢必较 - >红色气球飘向你way - > HA HA HA
但是,代码不是以所需的顺序输出。它输出如下: 检查验证 - >获取用户 - >红气球漂流的方式 - >哈哈哈
所以我想弄明白为什么'PENNYWISE'不显示。任何指导将不胜感激。
它应该按照预期给出输出,尝试'const setText =(text)=> div.textContent + = text }'。这将concat所有输出到你的div – Nemani