Skip to content

Commit

Permalink
util: add internal createInvertedPromise()
Browse files Browse the repository at this point in the history
The pattern of resolving/rejecting a Promise from outside of its
executor happens numerous times throughout the codebase (more than
what is updated here in fact). This commit abstracts that logic
into an internal utility function.
  • Loading branch information
cjihrig committed Jan 27, 2021
1 parent 7016c61 commit ef29ef3
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 16 deletions.
8 changes: 2 additions & 6 deletions lib/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const {
const {
promisify,
convertToValidSignal,
createInvertedPromise,
getSystemErrorName
} = require('internal/util');
const { isArrayBufferView } = require('internal/util/types');
Expand Down Expand Up @@ -184,12 +185,7 @@ function exec(command, options, callback) {

const customPromiseExecFunction = (orig) => {
return (...args) => {
let resolve;
let reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
const { promise, resolve, reject } = createInvertedPromise();

promise.child = orig(...args, (err, stdout, stderr) => {
if (err !== null) {
Expand Down
12 changes: 2 additions & 10 deletions lib/internal/blob.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const {
} = require('internal/util/types');

const {
createInvertedPromise,
customInspectSymbol: kInspect,
emitExperimentalWarning,
} = require('internal/util');
Expand Down Expand Up @@ -56,15 +57,6 @@ const kLength = Symbol('kLength');

let Buffer;

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

function lazyBuffer() {
if (Buffer === undefined)
Buffer = require('buffer').Buffer;
Expand Down Expand Up @@ -210,7 +202,7 @@ class Blob extends JSTransferable {
promise,
resolve,
reject
} = deferred();
} = createInvertedPromise();
job.ondone = (err, ab) => {
if (err !== undefined)
return reject(new AbortError());
Expand Down
12 changes: 12 additions & 0 deletions lib/internal/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -420,11 +420,23 @@ function sleep(msec) {
_sleep(msec);
}

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

return { promise, resolve, reject };
}

module.exports = {
assertCrypto,
cachedResult,
convertToValidSignal,
createClassWrapper,
createInvertedPromise,
decorateErrorStack,
deprecate,
emitExperimentalWarning,
Expand Down

0 comments on commit ef29ef3

Please sign in to comment.