Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

promise.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const nativePromisePrototype = (async () => {})().constructor.prototype;
  3. const descriptors = ['then', 'catch', 'finally'].map(property => [
  4. property,
  5. Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)
  6. ]);
  7. // The return value is a mixin of `childProcess` and `Promise`
  8. const mergePromise = (spawned, promise) => {
  9. for (const [property, descriptor] of descriptors) {
  10. // Starting the main `promise` is deferred to avoid consuming streams
  11. const value = typeof promise === 'function' ?
  12. (...args) => Reflect.apply(descriptor.value, promise(), args) :
  13. descriptor.value.bind(promise);
  14. Reflect.defineProperty(spawned, property, {...descriptor, value});
  15. }
  16. return spawned;
  17. };
  18. // Use promises instead of `child_process` events
  19. const getSpawnedPromise = spawned => {
  20. return new Promise((resolve, reject) => {
  21. spawned.on('exit', (exitCode, signal) => {
  22. resolve({exitCode, signal});
  23. });
  24. spawned.on('error', error => {
  25. reject(error);
  26. });
  27. if (spawned.stdin) {
  28. spawned.stdin.on('error', error => {
  29. reject(error);
  30. });
  31. }
  32. });
  33. };
  34. module.exports = {
  35. mergePromise,
  36. getSpawnedPromise
  37. };