创建一个接受回调并返回承诺的 api [英] Create an api which accepts a callback, and also returns a promise

查看:55
本文介绍了创建一个接受回调并返回承诺的 api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试升级现有的 api 以支持 promises,但我想保持向后兼容性.所以,假设这是我的 api:

So I'm trying to upgrade an existing api to support promises, but I want to maintain backwards compatibility. So, let's say this is my api:

module.exports = {

    deliverPost: function(callback) {

        someAsyncFunction(function(err) {

            if (err)
                console.log(err);

            callback(err);
        });
    }
}

太好了,我可以调用它并传递回调,一切正常.

That's great, I can call it and pass a callback, and everything works.

现在我们对 Promise 做同样的事情:

Now we do the same thing with promises:

var q = require('q');

module.exports = {

    deliverPost: function() {

        return q.nfcall(someAsyncFunction).catch(function(err) {

            console.log(err);
            throw err;
        });
    }
}

太好了,现在它返回一个承诺,但我的问题是,这个 api 的任何旧客户端都希望能够传入回调!

Great, now it returns a promise, but my problem is, any old clients of this api expect to be able to pass in a callback!

所以我真正需要的是这样的:

So what I really need is something like this:

var q = require('q');

module.exports = {

    deliverPost: function(callback) {

        return q.nfcall(someAsyncFunction).catch(function(err) {

            console.log(err);
            throw err;

        }).attachNodeStyleCallback(callback);
    }
}

所以新调用者可以利用 promise 支持,但如果您传入回调,一切仍然有效.

So new callers can leverage the promise support, but everything still works if you pass in a callback.

这是一个使用的模式,例如jQuery.ajax -- 我如何用 Q.js 做同样的事情?

This is a pattern used by, e.g. jQuery.ajax -- how can I do the same with Q.js?

这里是一个attachNodeStyleCallback的实现供参考:

Here's an implementation of attachNodeStyleCallback for reference:

q.makePromise.prototype.attachNodeStyleCallback = function(callback) {

    if (!callback)
        return this;

    return this.then(function(result) {

        callback(null, result);
        return result;

    }, function(err) {

        callback(err);
        throw err;
    })
}

推荐答案

答案是使用promise.nodeify:

var q = require('q');

module.exports = {

    deliverPost: function(callback) {

        return q.nfcall(someAsyncFunction).catch(function(err) {

            console.log(err);
            throw err;

        }).nodeify(callback);
    }
}

这篇关于创建一个接受回调并返回承诺的 api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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