javascript - 有没有一种方法可以结合 Bluebird 的 `then` 和 `catch` 功能?

标签 javascript promise bluebird

鉴于,我有一些这样的代码:

// code bits to be executed
var X = ...;
var pre = ...;
var success = ...;
var error = ...;
var post = ...;

我会像这样用 Bluebird 运行它:

X
.then(function(val) {
    pre(val);
    success(val);
    post(val);
})
.catch(function(err) {
    pre();
    error(err);
    post();
});

我正在寻找更简单的东西(这样,我可以定义更少的 function),按照以下行:

X
.complete(function(err, val) {
    pre(val);
    if (err) {
        error(err);
    }
    else {
        success(val);
    }
    post(val);
});

请注意,我不能使用 finally,因为它没有参数,errval 都没有。 另请注意,在发生错误时,val 被假定为 nullundefined

PS:越想越有感觉CoffeeScript可能会解决冗长的问题,同时保持整洁(将 if 排除在外并保持“可链接”)...

最佳答案

是的,你可以

您可以使用 nodeify 跳出 promise 链回到回调区域,它采用节点错误返回,例如:

.nodeify(function(err, val) {
    pre(val);
    if (err) {
        error(err);
    }
    else {
        success(val);
    }
    post(val);
});

这对于需要公开类似接口(interface)的节点错误返回的代码很有用。

但你可能不应该

但是,我不认为在这里使用 .nodeify 是个好主意 - 相反你可以这样做:

.finally(pre) // you always need this
.then(success, error) // call success and error and recover
.then(post); // post, this requires that `success` also returns val 

一般来说,您想要一个成功/失败函数——这叫做The .then(success, fail) anti-pattern并指出您应该考虑重构您的代码以接受 promise 。

返回 promise

通常,您可以返回 promise ,而不是像您的示例中那样接受成功和错误回调 - 所以如果您的函数是:

function doStuff(success, error){
    x().then(moreStuff).then(success, error)
}

你使用它的方式如下:doStuff(success, error)

你可以这样写:

function doStuff(){
    return x().then(moreStuff)
}

然后像 doStuff().then(...) 一样使用它,这样可以更轻松地链接、聚合和操作 promise。

处理器模式

pre/post 的常见模式是disposer 模式 - 例如“pre”是打开数据库连接,“post”是关闭数据库连接。这可以表示为:

function withHandle(fn){
    var handle;
    return pre().then(function(resource){ // obtain the resource
       handle = resource; // keep a handle
       return resource;
    }).
    then(fn). // run the actual code for that resource
    finally(function(){
       return handle.close(); // close the resource
    });
}

然后像这样使用:

withHandle(function(handle){
     return handle.query("Give me the first user"); 
}).then(function(result){
    // access result here, the handle is closed, can attach `catch`
});

关于javascript - 有没有一种方法可以结合 Bluebird 的 `then` 和 `catch` 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27729674/

相关文章:

javascript - 如何解析括号内有多个值的 JS Promise?

javascript - 可以在 Textarea 中撤消重做吗?

javascript - meteor @import css : Resource interpreted as Stylesheet but transferred with MIME type text/html:

javascript - 扩展 ES6 Promise 以将回调转换为延迟模式

c++ - std::promise 和 std::future 的非明显生命周期问题

javascript - 在 promise 数组之间添加延迟

javascript - 仅当代码在 3 秒内未执行时才执行 block

javascript - ".then(function(a){ return a; })"是 promise 的空操作吗?

javascript - 顽固的 Redux Action 发送空数组

javascript - 如何在带有 Moovweb SDK 的 Javascript 中移动 AJAX 内容?