避免推迟反模式 [英] Avoiding the deferred anti-pattern

查看:52
本文介绍了避免推迟反模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的代码:

I have some code that looks like this:

function foo() {

    var deferred;

    deferred = q.defer();

    doSomethingAsync()
        .then(function(result) {
            var resultTransformed = doSomethingSynchronousToTheResult(result);
            deferred.resolve(resultTransformed);
        });

    return deferred.promise;

};

也许:

function foo() {            
    return doSomethingAsync()
        .then(function(result) {
            return doSomethingSynchronousToTheResult(result);
        });       
};

以上内容是否可以确保将转换后的结果用于承诺链的下游?

Would the above ensure that the transformed result is used further down the promise chain?

我该如何重构以避免延迟的反模式?

How can I refactor this to avoid the deferred anti-pattern?

推荐答案

当创建新的冗余延迟对象以从承诺链内部进行解析时,将发生延迟反模式.

Deferred anti-pattern happens when new redundant deferred object is created to be resolved from inside an promise chain.

在您的情况下,您已经有一个Promise对象,因此只需要返回 doSomethingAsync()结果:

In your case you already have a Promise object, so you just need to return doSomethingAsync() result:

function foo() {
    return doSomethingAsync().then(function (result) {
        return doSomethingToTheResult(result);
    });
};

以上内容是否可以确保将转换后的结果用于承诺链的下游?

Would the above ensure that the transformed result is used further down the promise chain?

是的,确切地说,这是关于诺言的最酷的事情之一.

Yes, exactly, this is one of the coolest things about promises.

这篇关于避免推迟反模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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