如何解决JavaScript Async / Await逻辑表现为同步
如果我正确理解,则用关键字 async 声明的函数应该返回一个promise。对于 async3 函数,我们有10亿次迭代,这使返回值花费了更长的时间。分析下面的代码,我期望发生的事情是,通过调用 sync1 和 sync2 函数,立即登录控制台,然后出现async3函数日志。但是,我注意到的是 sync1 和 sync2 函数仅在 async3 结束后才记录。 async3 函数是否应该在另一个线程上或事件循环之外运行而不阻止运行时调用的其他函数的执行?
function sync1() {
console.log(1);
}
function sync2() {
console.log(2);
}
async function async3() {
let iteration = 0;
let number = 0;
while (iteration <= 1000000000) {
number = iteration;
iteration++;
}
return number;
}
sync1();
sync2();
async3().then((val) => console.log(val));
您能否阐明其行为的原因。我想念什么?
我的期望:
sync1(); // console logged immediately
sync2(); // console logged immediately
async3().then((val) => console.log(val)); // console logged moments later
当前发生的事情:
sync1(); // console logged after async3 is done sync2(); // console logged after async3 is done async3().then((val) => console.log(val)); // console logged after async3 is done
解决方法
请记住,JavaScript基本上是单线程的。
尽管async3
是异步的,但它的操作是完全同步的,并且占用大量CPU。一旦浏览器有一点空闲时间,输出将(以视觉方式)打印到控制台,但以下代码段:
while (iteration <= 1000000000) {
number = iteration;
iteration++;
}
使浏览器没有空闲时间,直到完成上述计算。
要让sync1
和sync2
立即登录,一种解决方案是让async3
每100,000次迭代(或某些迭代)暂停一次,然后等待setTimeout
,从而得出浏览器可以执行一些操作,例如向控制台显示内容,处理其他事件侦听器,呈现更改等等。
另一种解决方案是改为在 worker 中执行繁重的async3
函数,该函数位于单独的线程中,不会阻塞浏览器的主线程。>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。