Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving a Promise without calling the 'then'

I have this code that is part of a small API that I am writing for an NPM module called Poolio. The question I have seems to be a common question for those supporting error-first callbacks as well as promises- how do we support both while maintaining consisent APIs and consistent return values from the API? For example, if I conditionally return a promise from my API, depending on whether the consumer of my lib provides a callback, that is a little awkward in my opinion.

The consumer of the lib can provide a callback or use the Promise then function, but not both.

Here is a function exported by my lib, that I would like to promisify:

Pool.prototype.any = function (msg, cb) {

    var workId = this.counter++;
    var self = this;

    return new Promise(function (resolve, reject) {

        if (typeof cb === 'function') {
            self.resolutions.push({
                workId: workId,
                cb: cb
            });
        }
        else {
            self.resolutions.push({
                workId: workId,
                resolve: resolve,
                reject: reject
            });
        }

        if (this.available.length > 0) {
            var cp = this.available.shift();
            cp.workId = workId;
            cp.send(msg);
        }
        else {
            self.msgQueue.push({
                workId: workId,
                msg: msg
            });
        }
    });

};

my question is - if the user provides a callback function in the original function arguments, how can I resolve the promise without calling 'then'? Sorry it's hard to explain but hopefully you can understand.

also there is this interesting question: Do never resolved promises cause memory leak?

like image 822
Alexander Mills Avatar asked Oct 18 '22 17:10

Alexander Mills


1 Answers

It's actually very straightforward. Only you may have missed it because it's hidden amongst that tangle of code.

Basically you do this:

var promise = new Promise(function (resolve, reject) { /*....*/});

if (typeof cb === 'function') {
    promise.then(cb);
} else {
    return promise;
}
like image 147
slebetman Avatar answered Nov 03 '22 18:11

slebetman