我的 JavaScript 异步函数读取文件,然后将结果放入特定的 div 中。
async function loadContent( id, file ) {
var response = await fetch( file );
var text = await response.text();
document.getElementById( id ).innerHTML = text;
}
我现在这样使用它:
loadContent("pagesmaxspan", "../export/" + `<?php echo $randomid ?>` + ".variable");
但是当我尝试获取变量时它不起作用
var myvar = $("pagesmaxspan").textContent; // <<--- this does not work
延迟后,它看起来像这样:
var myvar = "";
setTimeout(function() {
myvar = $("pagesmaxspan").textContent;
}, 100);
如何在不使用 setTimeout
的情况下执行此操作?
最佳答案
当您调用 loadContent
时,那里没有 await
,因此您只需从 async
函数返回一个 Promise,代码就会继续执行.
这就是为什么上面@Patrick 的建议有效,将随后需要执行的代码放在 then
中。
关于javascript - 如何回调 async/await 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59773834/