Fixing a WebKit bug to see if promises are made of train tracks

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

Fixing a WebKit bug to see if promises are made of train tracks

Here is a program that, until July, never finished in Bun or Safari. 这是一个在七月之前,从未在 Bun 或 Safari 中运行结束的程序。

never.mjs
const p = Promise.resolve(1);
p.constructor = {
  get [Symbol.species]() {
    throw new Error("boom");
  },
};
console.log("before");
await p;
console.log("done");

Don’t worry if this looks confusing. The JavaScript spec says that because the getter throws an error, then await p should also throw, and so the program should crash. Node.js does, but Safari 26 and Bun 1.3.14 print ‘before’, report the error, and then hang. 如果这看起来令人困惑,请不必担心。JavaScript 规范指出,由于 getter 抛出了错误,那么 await p 也应该抛出错误,因此程序应该崩溃。Node.js 的表现确实如此,但 Safari 26 和 Bun 1.3.14 会打印“before”,报告错误,然后挂起。

node$ node never.mjs
before
Error: boom
exit 1

$ bun 1.3.14
$ bun never.mjs
before
error: boom

Safari 26 fails the same way as Bun: Safari 26 的失败方式与 Bun 相同:

Safari 26
const p = Promise.resolve(1);
p.constructor = {
  get [Symbol.species]() {
    throw new Error("boom");
  },
};
console.log("before");
await p;
console.log("done");

before
Error: boom

Bun and Safari both embed JavaScriptCore so the behaviour is the same - the promise is never settled! It is neither fulfilled nor rejected, so it stays pending forever. This was WebKit bug 318399. I fixed it in WebKit/WebKit#68749, and the fix was only +16 lines! Bun 和 Safari 都内置了 JavaScriptCore,因此行为是一样的——Promise 永远不会被结算(settled)!它既没有被兑现(fulfilled)也没有被拒绝(rejected),所以它会永远保持挂起状态。这就是 WebKit 的 318399 号 Bug。我在 WebKit/WebKit#68749 中修复了它,修复代码仅增加了 16 行!

What went wrong?

哪里出了问题?

What resolve does

resolve 的作用

Let’s quickly brush up on promises. When you construct a new promise in JavaScript, the engine creates two functions, resolve and reject, and passes them to the callback you pass to the promise constructor. 让我们快速复习一下 Promise。当你在 JavaScript 中构造一个新的 Promise 时,引擎会创建两个函数 resolve 和 reject,并将它们传递给你传给 Promise 构造函数的回调函数。

new-promise.js
new Promise((resolve, reject) => {
  console.log("I got my resolve function!", resolve);
  console.log("I got my reject function!", reject);
  resolve(42);
});
// In V8 this logs:
// I got my resolve function! ƒ () { [native code] }
// I got my reject function! ƒ () { [native code] }

The builtin helper function Promise.resolve(value) does the same thing by constructing a promise and immediately calling resolve with the value you passed (with the exception that if value is a promise, and has a .constructor property equal to Promise, it is returned as is). A simple userland implementation would look like this: 内置的辅助函数 Promise.resolve(value) 通过构造一个 Promise 并立即使用你传入的值调用 resolve 来实现同样的操作(例外情况是,如果 value 本身是一个 Promise,且其 .constructor 属性等于 Promise,则直接返回该值)。一个简单的用户空间实现如下所示:

promise-resolve.js
function PromiseDotResolve(value) {
  if (value instanceof Promise && value.constructor === Promise) {
    return value;
  }
  return new Promise(resolve => resolve(value));
}

The same is also true for literally writing await 42. The engine creates a promise and immediately calls resolve(42), just like Promise.resolve() does, and the same exception applies. 直接写 await 42 也是如此。引擎会创建一个 Promise 并立即调用 resolve(42),就像 Promise.resolve() 所做的那样,同样的例外规则也适用。

Many folks think of a promise as a value that can end in two ways - fulfilled with a value or rejected with a reason. This is a reasonable approximation since it maps pretty closely to how using promises actually feels when writing JavaScript day-to-day. Therefore, a naive implementation of a promise might look like this: 许多人认为 Promise 是一个可以以两种方式结束的值——以一个值兑现(fulfilled)或以一个原因拒绝(rejected)。这是一个合理的近似理解,因为它非常贴近日常编写 JavaScript 时使用 Promise 的实际感受。因此,一个简单的 Promise 实现可能如下所示:

mediocre-promise.ts
type PromiseState<T> =
  | {type: 'pending'}
  | {type: 'resolved', value: T}
  | {type: 'rejected', value: unknown};

class MediocrePromise<T> {
  private state: PromiseState<T> = {type: 'pending'};
  private callbacks: Array<() => void> = []; // registered by .then()

  private resolve(value: T) {
    this.settle({type: 'resolved', value});
  }

  private reject(reason: unknown) {
    this.settle({type: 'rejected', value: reason});
  }

  private settle(state: PromiseState<T>) {
    this.state = state;
    for (const callback of this.callbacks) callback();
  }
  // For example's sake this is missing `constructor`, `then`, etc.
}

I’ve called it MediocrePromise. It has a pending state, a way to resolve with a value, and a way to reject with a reason. It even has a list of callbacks to run, just like a real promise! Is this a good implementation? 我称之为 MediocrePromise(平庸的 Promise)。它有一个挂起状态,一种用值来 resolve 的方法,以及一种用原因来 reject 的方法。它甚至有一个要运行的回调列表,就像真正的 Promise 一样!这是一个好的实现吗?

Sadly, no. It is not a good implementation. MediocrePromise misses an important difference between how resolving and rejecting work. 遗憾的是,并不是。这不是一个好的实现。MediocrePromise 忽略了 resolve 和 reject 工作方式之间的一个重要区别。

Let’s start with rejections. Rejecting a promise is simple! Calling reject(reason) marks the promise as rejected, with reason as the rejected value. Excellent! MediocrePromise implements rejections correctly! 让我们从拒绝(rejections)开始。拒绝一个 Promise 很简单!调用 reject(reason) 将 Promise 标记为已拒绝,并将 reason 作为拒绝值。太棒了!MediocrePromise 正确地实现了拒绝功能!

Resolving is more complex. Calling resolve(value) does not store value straight away. First, it checks whether value has a .then() method. If it doesn’t (e.g. a number, a string, an object without one, ..) the promise is fulfilled with value and we are done. Otherwise, if it does have a .then() method, value is treated like another promise. Our original promise is not settled yet and instead, resolve passes itself and the reject function to value.then(resolve, reject). Whichever of those functions value.then() eventually calls is what settles the promise. Sorry, that was a mouthful. There’s a diagram in a sec to explain. Bear with me. 解析(Resolving)则复杂得多。调用 resolve(value) 不会立即存储该值。首先,它会检查 value 是否具有 .then() 方法。如果没有(例如数字、字符串、没有该方法的对象等),Promise 就会以该值兑现,我们就完成了。否则,如果它确实有 .then() 方法,value 就会被当作另一个 Promise 处理。我们最初的 Promise 尚未结算,相反,resolve 会将自身和 reject 函数传递给 value.then(resolve, reject)。value.then() 最终调用哪一个函数,就决定了该 Promise 的结算结果。抱歉,这有点拗口。稍后会有图表来解释。请耐心等待。

The resolve function is defined in the spec as the resolve procedure. To find out whether value has a .then, it reads value.then, and a property read can run a getter, and a getter can throw (just like in our program at the beginning). So, looking for a .then() method on some value can result in three possible outcomes: resolve 函数在规范中被定义为“解析过程”。为了找出 value 是否有 .then,它会读取 value.then,而属性读取可能会运行一个 getter,getter 可能会抛出错误(就像我们开头的程序中那样)。因此,在某个值上查找 .then() 方法可能会导致三种可能的结果:

Our MediocrePromise is missing the extra check and additional behaviour! 我们的 MediocrePromise 缺少了额外的检查和附加行为!

This asymmetry exists because a failure is not a pending operation. When something fails, you already have the reason in your code (presumably an error)! So you can call reject(reason) immediately. This is not the case for the happy path of resolving, where a useful value might arrive later: 这种不对称性存在的原因是,失败不是一个挂起的操作。当某事失败时,你的代码中已经有了原因(通常是一个错误)!所以你可以立即调用 reject(reason)。但在解析的“快乐路径”(happy path)中情况并非如此,因为有用的值可能会稍后到达:

reject(new Error("bad request")); // the reason is right here
resolve(response.json()); // the body is still arriving

This is why the extra behaviour is only implemented in resolve. 这就是为什么额外的行为只在 resolve 中实现的原因。

In the path where value.then is a function, the spec considers value to be a thenable. Promises are thenables, since they have a .then() method. Any other object with a .then() method is a thenable too. Thenables work everywhere a promise would. 在 value.then 是一个函数的情况下,规范将 value 视为一个“thenable”。Promise 是 thenable,因为它们有一个 .then() 方法。任何其他具有 .then() 方法的对象也是 thenable。Thenable 在任何可以使用 Promise 的地方都能工作。

Simply put: a thenable is any value with a .then() method. Therefore, any promise is also a thenable. 简而言之:thenable 是任何具有 .then() 方法的值。因此,任何 Promise 也都是一个 thenable。

For example: 例如:

// `thenable` is not a promise!
const thenable = {
  // resolve(thenable) calls this with the outer promise's resolve and reject
  then(resolve, _reject) {
    resolve(42);
  },
};

// resolve() called with the thenable
await new Promise(resolve => resolve(thenable)); // 42

// a .then callback returning the thenable
await Promise.resolve().then(() => thenable); // 42