1 |
|
2 | const nativePromisePrototype = (async () => {})().constructor.prototype;
|
3 |
|
4 | const descriptors = ['then', 'catch', 'finally'].map(property => [
|
5 | property,
|
6 | Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),
|
7 | ]);
|
8 |
|
9 |
|
10 | export const mergePromise = (spawned, promise) => {
|
11 | for (const [property, descriptor] of descriptors) {
|
12 |
|
13 | const value = typeof promise === 'function'
|
14 | ? (...args) => Reflect.apply(descriptor.value, promise(), args)
|
15 | : descriptor.value.bind(promise);
|
16 |
|
17 | Reflect.defineProperty(spawned, property, {...descriptor, value});
|
18 | }
|
19 | };
|
20 |
|
21 |
|
22 | export const getSpawnedPromise = spawned => new Promise((resolve, reject) => {
|
23 | spawned.on('exit', (exitCode, signal) => {
|
24 | resolve({exitCode, signal});
|
25 | });
|
26 |
|
27 | spawned.on('error', error => {
|
28 | reject(error);
|
29 | });
|
30 |
|
31 | if (spawned.stdin) {
|
32 | spawned.stdin.on('error', error => {
|
33 | reject(error);
|
34 | });
|
35 | }
|
36 | });
|