Javascript Promise - spread and add other methods

Viewed 58

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.

3 Answers

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)

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

Related