本文译者为 360 奇舞团前端开发工程师
原文标题:ECMAScript 2024 feature: Promise.withResolvers()
原文作者:Dr. Axel Rauschmayer
原文地址:https://2ality.com/2024/05/proposal-promise-with-resolvers.html#why-not-promise-deferred
本文将着重探讨 ECMAScript 2024 年的新特性之一 -- "Promise.withResolvers"(由 Peter Klecha 提出)。该特性提供了一种直接创建 Promise 的新方法,可替代 new Promise(...)。
在使用 Promise.withResolvers() 之前,只有一种方法可以直接创建 Promise - 通过以下模式:
const promise = new Promise(
(resolve, reject) => {
// ---
}
);
之所以这样做,根据 JavaScript 的 Promise API 设计团队的 Domenic Denicola 的说法是因为:
doThingsWith(p);
那么我们就可以确保,这个消费者不会扰乱构造函数向我们透露的任何内部信息。这有别于在 p 上放置任何人都可以调用的resolve和reject。
举例来说,让我们将基于回调的函数转换为基于许诺的函数(注意,Node.js 确实有一个完整的基于许诺的 API,即 node:fs/promises)。
以下代码展示了使用基于回调的函数 fs.readFile() 的场景:
import * as fs from 'node:fs';
fs.readFile('some-file.txt', 'utf-8', (error, result) => {
if (error !== null) {
console.error(error);
return;
}
assert.equal(
result,
'Content of some-file.txt'
);
});
接下来让我们实现一个基于 Promise 的 fs.readFile() 版本:
import * as fs from 'node:fs';
function readFileAsync(filePath, encoding) {
return new Promise(
(resolve, reject) => {
fs.readFile(filePath, encoding, (error, result) => {
if (error !== null) {
reject(error);
return;
}
resolve(result);
});
}
);
}
assert.equal(
await readFileAsync('some-file.txt', 'utf-8'),
'Content of some-file.txt'
);
揭示构造器模式的一个限制是,settlement函数 resolve 和 reject 不能离开 Promise 构造器回调,也不能与 Promise 分开使用。通过以下静态工厂可以解决这个问题:
const { promise, resolve, reject } = Promise.withResolvers();、
适用工厂函数就会像是下面这样:
{
const { promise, resolve, reject } = Promise.withResolvers();
resolve('fulfilled');
assert.equal(
await promise,
'fulfilled'
);
}
{
const { promise, resolve, reject } = Promise.withResolvers();
reject('rejected');
try {
await promise;
} catch (err) {
assert.equal(err, 'rejected');
}
}
我们可以如下实现 Promise.withResolvers():
function promiseWithResolvers() {
let resolve;
let reject;
const promise = new Promise(
(res, rej) => {
// Executed synchronously!
resolve = res;
reject = rej;
});
return {promise, resolve, reject};
}
该提案指出了有多少代码库实现了这一功能(这也是为什么现在将其内置到语言中确实是一个好消息):React、Vue、Axios、TypeScript、Vite、Deno 标准库。
让我们重温一下之前实现的函数 readFileAsync()。使用新的 API,我们可以将其编写如下:
import * as fs from 'node:fs';
function readFileAsync(filePath, encoding) {
const { promise, resolve, reject } = Promise.withResolvers();
fs.readFile(filePath, encoding, (error, result) => {
if (error !== null) {
reject(error);
return;
}
resolve(result);
});
return promise;
}
这段代码与我们使用 Promise 构造函数时的代码大致相同。让我们继续讨论构造函数无法处理的用例。
class OneElementQueue {
#promise = null;
#resolve = null;
constructor() {
const { promise, resolve } = Promise.withResolvers();
this.#promise = promise;
this.#resolve = resolve;
}
get() {
return this.#promise;
}
put(value) {
this.#resolve(value);
}
}
{ // Putting before getting
const queue = new OneElementQueue();
queue.put('one');
assert.equal(
await queue.get(),
'one'
);
}
{ // Getting before putting
const queue = new OneElementQueue();
setTimeout(
// Runs after `await` pauses the current execution context
() => queue.put('two'),
0
);
assert.equal(
await queue.get(),
'two'
);
}
PromiseQueue 是一个潜在的无限队列:
class PromiseQueue {
#frontPromise;
#backResolve;
constructor() {
const { promise, resolve } = Promise.withResolvers();
this.#frontPromise = promise;
this.#backResolve = resolve;
}
put(value) {
const { resolve, promise } = Promise.withResolvers();
// By resolving, we add another (pending) element
// to the end of the queue
this.#backResolve({ value, promise });
this.#backResolve = resolve;
}
get() {
return this.#frontPromise.then(
(next) => {
this.#frontPromise = next.promise;
return next.value;
}
);
}
}
{ // Putting before getting
const queue = new PromiseQueue();
queue.put('one');
queue.put('two');
assert.equal(
await queue.get(),
'one'
);
assert.equal(
await queue.get(),
'two'
);
}
{ // Getting before putting
const queue = new PromiseQueue();
setTimeout(
// Runs after `await` pauses the current execution context
() => {
queue.put('one');
queue.put('two');
},
0
);
assert.equal(
await queue.get(),
'one'
);
assert.equal(
await queue.get(),
'two'
);
}
每个队列元素都是 {value, promise} 的 Promise:
value 是存储在队列元素中的值。promise 是下一个(可能pending的)队列元素。队列的前面和后面:
前面是第一个队列元素(一个 Promise)。后面是最后一个(pending!)队列元素的resolve函数。
class AsyncIterQueue {
#frontPromise;
#backResolve;
constructor() {
const { promise, resolve } = Promise.withResolvers();
this.#frontPromise = promise;
this.#backResolve = resolve;
}
put(value) {
if (this.#backResolve === null) {
throw new Error('Queue is closed');
}
const { resolve, promise } = Promise.withResolvers();
this.#backResolve({ done: false, value, promise });
this.#backResolve = resolve;
}
close() {
this.#backResolve(
{ done: true, value: undefined, promise: null }
);
this.#backResolve = null;
}
next() {
if (this.#frontPromise === null) {
return Promise.resolve({done: true});
}
return this.#frontPromise.then(
(next) => {
this.#frontPromise = next.promise;
return {value: next.value, done: next.done};
}
);
}
[Symbol.asyncIterator]() {
return this;
}
}
{ // Putting before async iteration
const queue = new AsyncIterQueue();
queue.put('one');
queue.put('two');
queue.close();
assert.deepEqual(
await Array.fromAsync(queue),
['one', 'two']
);
}
{ // Async iteration before putting
const queue = new AsyncIterQueue();
setTimeout(
// Runs after `await` pauses the current execution context
() => {
queue.put('one');
queue.put('two');
queue.close();
},
0
);
assert.deepEqual(
await Array.fromAsync(queue),
['one', 'two']
);
}
与之前的实现相比,变化不大:
方法 .next() 和 .Symbol.asyncIterator是 AsyncIterable 接口的声名和实现。队列元素现在是{value, done, promise}的 Promise。.close()通过向队列添加最后一个元素,让我们可以关闭队列:{done: true, value: undefined, promise: null }
只有了解 Promises 历史的人才能理解 "deferred "这个名称:这是 jQuery 的 "Promise API" 中使用的名称。如果你是 JavaScript 的新手,这个名字对你来说没有任何意义。
通过 resolve() 解析 Promise 只意味着确定了它的"命运":
const {promise, resolve} = Promise.withResolvers();
resolve(123); // 解决了`promise`。
const {promise, resolve} = Promise.withResolvers();
resolve(new Promise(() => {}); // `promise` is forever pending
因此,resolve 和 reject 通常只能解析 Promise,而不会settle。
[图片来源:proposal-promise-with-resolvers:issues[1]]
此外,ECMAScript 规范将 resolve 和 reject 命名为 "resolving functions"。
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8