解决承诺而不叫'then' [英] Resolving a Promise without calling the 'then'

查看:54
本文介绍了解决承诺而不叫'then'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,这是我为名为Poolio的NPM模块编写的小型API的一部分。对于那些支持错误优先回调和Promise的人来说,我似乎是一个常见问题。在维护一致的API和API一致的返回值的同时,我们如何支持两者?例如,如果我有条件地从我的API中返回一个promise,这取决于我的lib的使用者是否提供了回调,那么我认为这有点尴尬。

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.

lib的使用者可以提供回调或使用Promise then函数,但不能同时使用两者。

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

这里是我的lib导出的一个函数,谨在此声明:

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?

推荐答案

实际上非常简单。

基本上,您可以这样做:

Basically you do this:

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

if (typeof cb === 'function') {
    promise.then(cb);
} else {
    return promise;
}

这篇关于解决承诺而不叫'then'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆