Skip to content

Commit

Permalink
lib: refactor project to use Promise.withResolvers
Browse files Browse the repository at this point in the history
  • Loading branch information
anonrig committed Sep 8, 2024
1 parent 8882a21 commit c69b907
Show file tree
Hide file tree
Showing 20 changed files with 81 additions and 88 deletions.
4 changes: 2 additions & 2 deletions lib/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const {
ObjectAssign,
ObjectDefineProperty,
ObjectPrototypeHasOwnProperty,
PromiseWithResolvers,
RegExpPrototypeExec,
SafeSet,
StringPrototypeIncludes,
Expand All @@ -47,7 +48,6 @@ const {

const {
convertToValidSignal,
createDeferredPromise,
getSystemErrorName,
kEmptyObject,
promisify,
Expand Down Expand Up @@ -237,7 +237,7 @@ function exec(command, options, callback) {

const customPromiseExecFunction = (orig) => {
return (...args) => {
const { promise, resolve, reject } = createDeferredPromise();
const { promise, resolve, reject } = PromiseWithResolvers();

promise.child = orig(...args, (err, stdout, stderr) => {
if (err !== null) {
Expand Down
4 changes: 2 additions & 2 deletions lib/internal/abort_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const {
ObjectDefineProperties,
ObjectDefineProperty,
PromiseResolve,
PromiseWithResolvers,
SafeFinalizationRegistry,
SafeSet,
Symbol,
Expand All @@ -26,7 +27,6 @@ const {
kWeakHandler,
} = require('internal/event_target');
const {
createDeferredPromise,
customInspectSymbol,
kEmptyObject,
kEnumerableProperty,
Expand Down Expand Up @@ -449,7 +449,7 @@ async function aborted(signal, resource) {
validateObject(resource, 'resource', kValidateObjectAllowObjects);
if (signal.aborted)
return PromiseResolve();
const abortPromise = createDeferredPromise();
const abortPromise = PromiseWithResolvers();
const opts = { __proto__: null, [kWeakHandler]: resource, once: true, [kResistStopPropagation]: true };
signal.addEventListener('abort', abortPromise.resolve, opts);
return abortPromise.promise;
Expand Down
6 changes: 3 additions & 3 deletions lib/internal/blob.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const {
ObjectSetPrototypeOf,
PromisePrototypeThen,
PromiseReject,
PromiseWithResolvers,
RegExpPrototypeExec,
RegExpPrototypeSymbolReplace,
StringPrototypeSplit,
Expand Down Expand Up @@ -47,7 +48,6 @@ const {
} = require('internal/util/types');

const {
createDeferredPromise,
customInspectSymbol: kInspect,
kEmptyObject,
kEnumerableProperty,
Expand Down Expand Up @@ -273,7 +273,7 @@ class Blob {
if (!isBlob(this))
return PromiseReject(new ERR_INVALID_THIS('Blob'));

const { promise, resolve, reject } = createDeferredPromise();
const { promise, resolve, reject } = PromiseWithResolvers();
const reader = this[kHandle].getReader();
const buffers = [];
const readNext = () => {
Expand Down Expand Up @@ -340,7 +340,7 @@ class Blob {
this.pendingPulls = [];
},
pull(c) {
const { promise, resolve, reject } = createDeferredPromise();
const { promise, resolve, reject } = PromiseWithResolvers();
this.pendingPulls.push({ resolve, reject });
const readNext = () => {
reader.pull((status, buffer) => {
Expand Down
6 changes: 3 additions & 3 deletions lib/internal/fs/watchers.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const {
FunctionPrototypeCall,
ObjectDefineProperty,
ObjectSetPrototypeOf,
PromiseWithResolvers,
Symbol,
} = primordials;

Expand All @@ -15,7 +16,6 @@ const {
},
} = require('internal/errors');
const {
createDeferredPromise,
kEmptyObject,
} = require('internal/util');

Expand Down Expand Up @@ -325,7 +325,7 @@ async function* watch(filename, options = kEmptyObject) {
throw new AbortError(undefined, { cause: signal?.reason });

const handle = new FSEvent();
let { promise, resolve, reject } = createDeferredPromise();
let { promise, resolve, reject } = PromiseWithResolvers();
const oncancel = () => {
handle.close();
reject(new AbortError(undefined, { cause: signal?.reason }));
Expand Down Expand Up @@ -368,7 +368,7 @@ async function* watch(filename, options = kEmptyObject) {

while (!signal?.aborted) {
yield await promise;
({ promise, resolve, reject } = createDeferredPromise());
({ promise, resolve, reject } = PromiseWithResolvers());
}
throw new AbortError(undefined, { cause: signal?.reason });
} finally {
Expand Down
13 changes: 13 additions & 0 deletions lib/internal/per_context/primordials.js
Original file line number Diff line number Diff line change
Expand Up @@ -744,5 +744,18 @@ primordials.SafeStringPrototypeSearch = (str, regexp) => {
return match ? match.index : -1;
};

// TODO(@anonrig): Remove this when V8 removes the flag to disable Promise.withResolvers()
// eslint-disable-next-line node-core/prefer-primordials
primordials.PromiseWithResolvers = Promise.withResolvers || (() => {
let resolve;
let reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});

return { promise, resolve, reject };
});

ObjectSetPrototypeOf(primordials, null);
ObjectFreeze(primordials);
6 changes: 3 additions & 3 deletions lib/internal/streams/duplexify.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const {
FunctionPrototypeCall,
PromiseWithResolvers,
} = primordials;

const {
Expand All @@ -27,7 +28,6 @@ const { destroyer } = require('internal/streams/destroy');
const Duplex = require('internal/streams/duplex');
const Readable = require('internal/streams/readable');
const Writable = require('internal/streams/writable');
const { createDeferredPromise } = require('internal/util');
const from = require('internal/streams/from');

const {
Expand Down Expand Up @@ -209,7 +209,7 @@ module.exports = function duplexify(body, name) {
};

function fromAsyncGen(fn) {
let { promise, resolve } = createDeferredPromise();
let { promise, resolve } = PromiseWithResolvers();
const ac = new AbortController();
const signal = ac.signal;
const value = fn(async function*() {
Expand All @@ -221,7 +221,7 @@ function fromAsyncGen(fn) {
if (done) return;
if (signal.aborted)
throw new AbortError(undefined, { cause: signal.reason });
({ promise, resolve } = createDeferredPromise());
({ promise, resolve } = PromiseWithResolvers());
yield chunk;
}
}(), { signal });
Expand Down
4 changes: 2 additions & 2 deletions lib/internal/test_runner/harness.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const {
ArrayPrototypePush,
FunctionPrototypeBind,
PromiseResolve,
PromiseWithResolvers,
SafeMap,
SafePromiseAllReturnVoid,
} = primordials;
Expand All @@ -26,7 +27,6 @@ const {
shouldColorizeTestFiles,
} = require('internal/test_runner/utils');
const { queueMicrotask } = require('internal/process/task_queues');
const { createDeferredPromise } = require('internal/util');
const { bigint: hrtime } = process.hrtime;
const resolvedPromise = PromiseResolve();
const testResources = new SafeMap();
Expand All @@ -35,7 +35,7 @@ let globalRoot;
testResources.set(reporterScope.asyncId(), reporterScope);

function createTestTree(rootTestOptions, globalOptions) {
const buildPhaseDeferred = createDeferredPromise();
const buildPhaseDeferred = PromiseWithResolvers();
const harness = {
__proto__: null,
buildPromise: buildPhaseDeferred.promise,
Expand Down
4 changes: 2 additions & 2 deletions lib/internal/test_runner/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const {
ObjectAssign,
PromisePrototypeThen,
PromiseResolve,
PromiseWithResolvers,
SafeMap,
SafePromiseAll,
SafePromiseAllReturnVoid,
Expand Down Expand Up @@ -59,7 +60,6 @@ const { getInspectPort, isUsingInspector, isInspectorMessage } = require('intern
const { isRegExp } = require('internal/util/types');
const { pathToFileURL } = require('internal/url');
const {
createDeferredPromise,
getCWDURL,
kEmptyObject,
} = require('internal/util');
Expand Down Expand Up @@ -688,7 +688,7 @@ function run(options = kEmptyObject) {
};
} else {
runFiles = async () => {
const { promise, resolve: finishBootstrap } = createDeferredPromise();
const { promise, resolve: finishBootstrap } = PromiseWithResolvers();

await root.runInAsyncScope(async () => {
const parentURL = getCWDURL().href;
Expand Down
6 changes: 3 additions & 3 deletions lib/internal/test_runner/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const {
ObjectSeal,
PromisePrototypeThen,
PromiseResolve,
PromiseWithResolvers,
ReflectApply,
RegExpPrototypeExec,
SafeMap,
Expand Down Expand Up @@ -49,7 +50,6 @@ const {
isTestFailureError,
} = require('internal/test_runner/utils');
const {
createDeferredPromise,
kEmptyObject,
once: runOnce,
} = require('internal/util');
Expand Down Expand Up @@ -133,7 +133,7 @@ function lazyAssertObject(harness) {
}

function stopTest(timeout, signal) {
const deferred = createDeferredPromise();
const deferred = PromiseWithResolvers();
const abortListener = addAbortListener(signal, deferred.resolve);
let timer;
let disposeFunction;
Expand Down Expand Up @@ -775,7 +775,7 @@ class Test extends AsyncResource {
// pending for later execution.
this.reporter.enqueue(this.nesting, this.loc, this.name);
if (this.root.harness.buildPromise || !this.parent.hasConcurrency()) {
const deferred = createDeferredPromise();
const deferred = PromiseWithResolvers();

deferred.test = this;
this.parent.addPendingSubtest(deferred);
Expand Down
4 changes: 2 additions & 2 deletions lib/internal/test_runner/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const {
NumberParseInt,
NumberPrototypeToFixed,
ObjectGetOwnPropertyDescriptor,
PromiseWithResolvers,
RegExp,
RegExpPrototypeExec,
SafeMap,
Expand All @@ -27,7 +28,6 @@ const { AsyncResource } = require('async_hooks');
const { relative } = require('path');
const { createWriteStream } = require('fs');
const { pathToFileURL } = require('internal/url');
const { createDeferredPromise } = require('internal/util');
const { getOptionValue } = require('internal/options');
const { green, yellow, red, white, shouldColorize } = require('internal/util/colors');

Expand Down Expand Up @@ -57,7 +57,7 @@ const kDefaultPattern = `**/{${ArrayPrototypeJoin(kPatterns, ',')}}.?(c|m)js`;

function createDeferredCallback() {
let calledCount = 0;
const { promise, resolve, reject } = createDeferredPromise();
const { promise, resolve, reject } = PromiseWithResolvers();
const cb = (err) => {
calledCount++;

Expand Down
12 changes: 0 additions & 12 deletions lib/internal/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -559,17 +559,6 @@ function sleep(msec) {
_sleep(msec);
}

function createDeferredPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});

return { promise, resolve, reject };
}

// https://heycam.github.io/webidl/#define-the-operations
function defineOperation(target, name, method) {
ObjectDefineProperty(target, name, {
Expand Down Expand Up @@ -896,7 +885,6 @@ module.exports = {
cachedResult,
convertToValidSignal,
createClassWrapper,
createDeferredPromise,
decorateErrorStack,
defineOperation,
defineLazyProperties,
Expand Down
12 changes: 6 additions & 6 deletions lib/internal/webstreams/adapters.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const {
ObjectEntries,
PromisePrototypeThen,
PromiseResolve,
PromiseWithResolvers,
SafePromiseAll,
SafePromisePrototypeFinally,
SafeSet,
Expand Down Expand Up @@ -64,7 +65,6 @@ const {
} = require('internal/errors');

const {
createDeferredPromise,
kEmptyObject,
normalizeEncoding,
} = require('internal/util');
Expand Down Expand Up @@ -213,7 +213,7 @@ function newWritableStreamFromStreamWritable(streamWritable) {

async write(chunk) {
if (streamWritable.writableNeedDrain || !streamWritable.write(chunk)) {
backpressurePromise = createDeferredPromise();
backpressurePromise = PromiseWithResolvers();
return SafePromisePrototypeFinally(
backpressurePromise.promise, () => {
backpressurePromise = undefined;
Expand All @@ -227,7 +227,7 @@ function newWritableStreamFromStreamWritable(streamWritable) {

close() {
if (closed === undefined && !isWritableEnded(streamWritable)) {
closed = createDeferredPromise();
closed = PromiseWithResolvers();
streamWritable.end();
return closed.promise;
}
Expand Down Expand Up @@ -900,7 +900,7 @@ function newWritableStreamFromStreamBase(streamBase, strategy) {
}

function doWrite(chunk, controller) {
const promise = createDeferredPromise();
const promise = PromiseWithResolvers();
let ret;
let req;
try {
Expand Down Expand Up @@ -933,7 +933,7 @@ function newWritableStreamFromStreamBase(streamBase, strategy) {
},

close() {
const promise = createDeferredPromise();
const promise = PromiseWithResolvers();
const req = new ShutdownWrap();
req.oncomplete = () => promise.resolve();
const err = streamBase.shutdown(req);
Expand Down Expand Up @@ -1000,7 +1000,7 @@ function newReadableStreamFromStreamBase(streamBase, strategy, options = kEmptyO
},

cancel() {
const promise = createDeferredPromise();
const promise = PromiseWithResolvers();
try {
ondone();
} catch (error) {
Expand Down
Loading

0 comments on commit c69b907

Please sign in to comment.