Skip to content

Commit

Permalink
Simplify mergePromise function (#403)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker authored and sindresorhus committed Dec 23, 2019
1 parent 3a276a8 commit 0e4da68
Showing 1 changed file with 14 additions and 16 deletions.
30 changes: 14 additions & 16 deletions lib/promise.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
'use strict';
const mergePromiseProperty = (spawned, promise, property) => {
// Starting the main `promise` is deferred to avoid consuming streams
const value = typeof promise === 'function' ?
(...args) => promise()[property](...args) :
promise[property].bind(promise);

Object.defineProperty(spawned, property, {
value,
writable: true,
enumerable: false,
configurable: true
});
};

const descriptors = ['then', 'catch', 'finally'].map(property => [
property,
Reflect.getOwnPropertyDescriptor(Promise.prototype, property)
]);

// The return value is a mixin of `childProcess` and `Promise`
const mergePromise = (spawned, promise) => {
mergePromiseProperty(spawned, promise, 'then');
mergePromiseProperty(spawned, promise, 'catch');
mergePromiseProperty(spawned, promise, 'finally');
for (const [property, descriptor] of descriptors) {
// Starting the main `promise` is deferred to avoid consuming streams
const value = typeof promise === 'function' ?
(...args) => Reflect.apply(descriptor.value, promise(), args) :
descriptor.value.bind(promise);

Reflect.defineProperty(spawned, property, {...descriptor, value});
}

return spawned;
};

Expand Down

0 comments on commit 0e4da68

Please sign in to comment.