worker 与页面线程
除非另行指定,浏览器应用会在 Web Worker 中运行模块。这决定了调用返回什么,以及页面是否需要等待。
演练场在页面自己的线程上运行模块。slowSum 运行期间,页面上的其他任何东西都无法运行:main.js 中的计时器一次也不会触发。在 worker 中,同样的调用会立即返回 Promise,页面也不会被阻塞。
这就是本教程中每次调用都有 await 的原因。initNative({ useWorker: false }) 会让模块留在页面线程上,在那里调用直接返回值,也可以传递回调函数;参见 Worker 模式。
试一试
去掉 slowSum 前的 await,然后打印 sum。在这里它仍然是一个数字;在 worker 中则会是一个 Promise。[■]native.h1#pragma once
// A call that takes a moment: the sum of the square roots of
// the numbers up to `count`.
double slowSum(int count);
[■]main.js2import { initNative, slowSum } from './native/native.h';
await initNative();
let ticks = 0;
const timer = setInterval(() => { ticks += 1; }, 1);
const sum = await slowSum(30_000_000);
clearInterval(timer);
console.log('sum:', Math.round(sum));
console.log('timer ticks while C++ ran:', ticks);