3

Is it possible to make the following function?

const method = () => {
    let _reject;
    const promise = new Promise((resolve, reject) => {
      _reject = reject;
      ...
    });
  
    return {
      ...promise,
      cancel: () => _reject('cancelled'),
    }
}

i.e. I can do something like:

const promise = method();
// now I have promise.then, promise.catch and promise.cancel

This is just an example; I want to be able to add extra properties to this "promise" object.

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • 1
    Keep in mind that this hypothetical `cancel()` method doesn't actually terminate the asynchronous code initiated by the promise constructor. – Patrick Roberts Dec 12 '20 at 07:28

3 Answers3

1

No, you can't spread a promise instance, as it would loose its prototype (methods), but you can trivially add properties to it like to any object:

promise.cancel = () => _reject('cancelled');
return promise;

(Note that I'm not saying this is a good idea)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

See this answer Extending a Promise in javascript

you might need extend your specialized Promise class

class CancellablePromise extends Promise {
   cancel(){ }
}
uke
  • 893
  • 4
  • 10
0

You can do the following:

const _resolve= Symbol('resolve');
const _reject= Symbol('reject');

class ExPromise extends Promise{
    constructor(executor) {
        let resolve, reject;

        super((_resolve, _reject) => {
            resolve = _resolve;
            reject = _reject;
            executor(resolve, reject);
        });

        this[_resolve]= resolve;
        this[_reject]= reject;
    }

    cancel(){
        this[_reject](new Error('canceled'));
    }
}

If you need cancellation of the nested promises or some other extra features, you can try the c-promise2 package

Dmitriy Mozgovoy
  • 1,419
  • 2
  • 8
  • 7