代码之家  ›  专栏  ›  技术社区  ›  jfriend00

在jQuery中获得已解决承诺的更好方法?

  •  3
  • jfriend00  · 技术社区  · 11 年前

    在jQuery中使用promise进行编程时,我有时需要从解析的promise开始,特别是在链接时 .then() 在这样的循环中,如 this answer :

    data.reduce(function(p, item) {
        return p.then(function() {
            return print(item);
        });
    }, $.Deferred().resolve().promise());
    

    因此,我知道我可以通过以下方式得到一个明确的承诺:

    $.Deferred().resolve().promise()
    

    但是,这看起来有点丑陋和浪费(三个函数调用)。有没有更好的方法(更少的代码,更少的函数调用)来在jQuery中获得已解决的承诺,或者更好的方法来编写 .reduce() 上面的循环?

    1 回复  |  直到 9 年前
        1
  •  3
  •   Benjamin Gruenbaum    11 年前

    首先,你不需要 .promise .jQuery延迟对象是 already also promises 所以 $.Deferred().resolve() 也会起作用。

    在我看来,这是jQuery最好的方法,因为它是显式的,但有更短的方法可以绕过它。我知道最短的方法是:

    $().promise(); // shorter but more hacky.
    
    $.Deferred().resolve(); // this will work and is what I'd do
    
    $.when(); // this is also a viable alternative 
    

    这相当短。当然,如果有可能的话,最好使用更好的promise库,因为jQuery promise不能保证有序的异步执行,并且不允许错误处理,而且如果有很多promise正在运行,那么处理速度会非常慢。

    当然,没有人阻止你围绕它编写实用方法:)