async await 在浏览器中真的是非阻塞的吗? [英] Is async await truly non-blocking in the browser?

查看:45
本文介绍了async await 在浏览器中真的是非阻塞的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 TypeScript 和原生 Promise 的 SPA 中使用该功能,我注意到即使我将长时间运行的函数重构为返回 Promise 的异步函数,UI 仍然没有响应.

I have been playing around with the feature in an SPA using TypeScript and native Promises, and I notice that even if I refactor a long-running function into an async function returning a promise, the UI is still unresponsive.

所以我的问题是:

  • 新的 async/await 功能究竟如何帮助避免阻塞浏览器中的 UI?在使用 async/await 实际获得响应式 UI 时,是否需要采取任何特殊的额外步骤?

  • How exactly does the new async/await feature help avoid blocking the UI in the browser? Are there any special extra steps one needs to take when using async/await to actually get a responsive UI?

有人可以创建一个小提琴来演示 async/await 如何帮助使 UI 具有响应性吗?

Can someone create a fiddle to demonstrate the how async/await helps to make the UI responsive?

async/await 与之前的异步功能(例如 setTimeout 和 XmlHttpRequest)有何关联?

How does async/await relate to prior async features such as setTimeout and XmlHttpRequest?

推荐答案

await p 安排在 promise p 解决时执行其余函数.仅此而已.

await p schedules execution of the rest of your function when promise p resolves. That's all.

async 允许您使用 await.这就是(几乎)它所做的一切(它还将您的结果包装在一个承诺中).

async lets you use await. That's (almost) all it does (It also wraps your result in a promise).

它们一起使非阻塞代码读起来像更简单的阻塞代码.他们不会取消阻止代码.

Together they make non-blocking code read like simpler blocking code. They don't unblock code.

对于响应式 UI,将 CPU 密集型工作卸载给 worker 线程,并将消息传递给它:

For a responsive UI, offload CPU-intensive work to a worker thread, and pass messages to it:

async function brutePrime(n) {
  function work({data}) {
    while (true) {
      let d = 2;
      for (; d < data; d++) {
        if (data % d == 0) break;
      }
      if (d == data) return self.postMessage(data);
      data++;
    }
  }

  let b = new Blob(["onmessage =" + work.toString()], {type: "text/javascript"});
  let worker = new Worker(URL.createObjectURL(b));
  worker.postMessage(n); 
  return await new Promise(resolve => worker.onmessage = e => resolve(e.data));
}

(async () => {
  let n = 700000000;
  for (let i = 0; i < 10; i++) {
    console.log(n = await brutePrime(n + 1));
  }
})().catch(e => console.log(e));

这篇关于async await 在浏览器中真的是非阻塞的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆