jquery 承诺的延迟

2024-01-12

我找不到delay or wait函数为jQuery承诺。我在 SO 上找到了一项功能(使用 jQuery.Deferred 避免嵌套 setTimeout 回调 https://stackoverflow.com/q/17983331/1048572):

function delay(time) {
    return function () {
        console.log("Delaying");
        var ret = new $.Deferred();
        setTimeout(function () {
            ret.resolve();
        }, time);
        return ret;
    };
}

而且,这就是我使用它的方式:

 run: function () {
        return $()
            .promise()
            .then(function () {
                console.log("call together");
                console.log("call together");    
            })
            .then(delay(2000))
            .then(function () {
                console.log("call first");
            })
            .then(delay(2000))
            .then(function () {
                console.log("call second");
            })
    }

我想扩展承诺或延迟对象,我可以这样写:

run: function () {
            return $()
                .promise()
                .then(function () {
                    console.log("call together");
                    console.log("call together");    
                })
                .delay(2000)
                .then(function () {
                    console.log("call first");
                })
                .delay(2000)
                .then(function () {
                    console.log("call second");
                })
        }

正如 @Bergi 所说,jQuery Deferreds/Promises 不能通过原型继承进行扩展。

相反,jQuery 采用的模型是允许使用以下语法扩展单个 Promise 实例:

deferred.promise(target);
//or, 
promise.promise(target); //(though the documentation doesn't make this clear)
// where `target` is an "object onto which the promise methods have to be attached"
// see https://api.jquery.com/deferred.promise/

通过使用一堆方法定义构造函数,任何 jQuery Deferred 或 Promise 都可以使用简单的语法进行扩展

.promise(Constructor())

在我未发布、未记录的 jQuery Promise Playground 中,构造函数被命名为$P并保存在 jQuery 命名空间中,因此我使用的实际语法是:

.promise($.$P())

您需要注意的是,在大多数情况下,没有必要调用$.$P()明确地,因为 Playground 包括$.when_()返回已扩展 Promise 的方法。

这是 Playground 的缩写版本,足以提供.delay()方法 :

(function($) {
    /* ***********************************
     * The $.$P function returns an object
     * designed to be extended with 
     * promise methods using the syntax :
     *    myDeferred.promise($.$P())
     *    myPromise.promise($.$P())
     * where `myDeferred`/`myPromise` 
     * are jQuery Deferred/Promise objects.
     * ***********************************/

    /* ***********************************
     * Methods
     * ***********************************/
    $.$P = function() {
        if (this instanceof $.$P) {
            return this;
        } else {
            return new $.$P();
        }
    };
    $.$P.prototype.then_ = function(fa, fb) {
        /* A promise method that is the same as .then()
         * but makes these extra methods available 
         * down-chain.
         */
        return this.then(fa||null, fb||null).promise($.$P());
    }
    $.$P.prototype.delay_ = function(ms) {
        /* A promise method that 
         * introduces a down-chain delay.
         */
        var promise = this;
        function f(method) {
            return function() { setTimeout(function(){ method.apply(null,this); }.bind(arguments), ms||0); };
        }
        return $.Deferred(function(dfrd) { 
            promise.then(f(dfrd.resolve), f(dfrd.reject));
        }).promise($.$P());
    }

    /* ***********************************
     * Utility functions
     * ***********************************/
    function consolidate(args) {
        /* Convert mixed promises/arrays_of_promises to single array.
         * Called by all the when_() methods below.
         */
        return Array.prototype.slice.apply(args).reduce(function(arr, current) {
            return arr.concat(current);
        }, []);
    }

    /* ***********************************
     * This section extends the jQuery namespace 
     * with a "jQuery.when_()" method.
     * ***********************************
     */
    $.extend({
        'when_': function() {
            return $.when.apply(null, consolidate(arguments)).promise($.$P()).then_(function() {
                return consolidate(arguments);
            });
        },
    });
})(jQuery);

完整的 Playground 还包括一大堆用于其他目的的静态方法和承诺实例方法,开发它们是游戏的本质。

使用游乐场的基本规则如下:

  • 所有 Playground 的静态方法和 Promise 方法都以下划线“_”结尾。
  • 静态方法,例如$.when_(),只需安装 Playground 即可使用。
  • 承诺链中的承诺通过包含静态方法来扩展,例如.when_(),或链接.promise($.$P()).
  • 在承诺链中,通过使用“..._”方法而不是标准方法,扩展保持可用(沿着链),例如.then_()代替.then().

因此,以下是如何使用它来施加问题所需的延迟:

jQuery(function($) {
    var MYNAMESPACE = {
        run: function (t) {
            return $.when_()
            .then_(function () {
                log("call together");
                log("call together");    
            })
            .delay_(t)
            .then_(function () {
                log("call first");
            })
            .delay_(t)
            .then_(function () {
                log("call second");
            });
        }
    }
});

DEMO http://jsfiddle.net/r6hrtv1q/

在演示中,按钮的单击处理程序进一步指示了如何使用 Playground。

使用游乐场的限制条件:

  • 正如我所说 - 这是一个操场.
  • 作为 jQuery 的适配器,而不是补丁,它在某些地方效率非常低。最糟糕的方面是,某些方法除了返回的承诺之外还创建了中间承诺。
  • 未按照生产代码中使用所需的标准进行测试,因此请谨慎使用。

最后,如果您决定使用 jQuery 实现延迟,则仅考虑上述内容。使用已经有的承诺库要简单得多.delay() method.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jquery 承诺的延迟 的相关文章

随机推荐

  • 想要使用 ActionSherlockBar 添加选项卡

    我想用 ActionSherlockBar 添加选项卡所以我使用了一些代码 资源 https stackoverflow com questions 13640512 android actionbar sherlock with tabs
  • Graphviz 未在 jupyter 笔记本 python = 3.6 中运行?

    我正在尝试运行 graphviz 以查看 jupyter 笔记本上的点文件 其中已导入 dot exe 路径的路径 G anaconda3 envs tensorflowgpu Library bin graphviz G anaconda
  • 将数据帧随机分成 n 个相等的部分

    假设我有一个不同行数的数据帧列表 AB df data frame replicate 2 sample 0 130 201 rep TRUE BC df data frame replicate 2 sample 0 130 200 re
  • ASP.NET 路由是否可用于为 .ashx (IHttpHander) 处理程序创建“干净”的 URL?

    我有一些使用普通旧式的 REST 服务IHttpHandlers 我想生成更清晰的 URL 这样路径中就没有 ashx 有没有办法使用 ASP NET 路由来创建映射到 ashx 处理程序的路由 我以前见过这些类型的路线 Route to
  • 如何在sql中选择连续日期

    是否有任何函数可以检查连续日期 我在处理以下问题时遇到问题 我的桌子上有一个datetime包含以下数据的列 2015 03 11 2015 03 12 2015 03 13 2015 03 16 指定开始日期为2015 3 11和结束日期
  • FireBase API 是否有未缩小的 JavaScript 版本?

    我正在为通过 FireBase 提供 API 的设备开发一个界面 但我没有使用 Java JavaScript 或 FireBase 提供的库的任何其他语言 我正在使用 Lua 虽然我可以轻松实现 REST API 但我希望能够使用 Fir
  • Google APIs Explorer 未从我的应用程序引擎应用程序中找到可用的 ApiMethod

    我有一个可以正常编译的 App Engine 应用程序 我使用本地主机上的 Google Apis Explorer 测试方法调用 https developers google com apis explorer base http lo
  • 临时表在同一连接池上的多个请求中是否唯一?

    我有以下存储过程 它使用临时表批量导入数据 我知道临时表对于每个会话都是唯一的 但是我想知道我的应用程序是否使用线程并向存储过程发出多个并发请求 使用应用程序池中的相同 sql 连接 它们最终会引用相同的临时表吗 CREATE PROCED
  • Rhino - 将 javascript 对象传递给 java

    我对 Rhino 很陌生 我的问题是如何实现以下目标 假设我有一个 javascript 对象 它遵循如下所示的内容 我可以在 java 中使用它 var myObject new Object myObject string1 Hello
  • 没有jquery的自定义滚动条

    我正在寻找一个无需 jquery 即可工作的自定义滚动条 我不能使用 jquery 因为其他东西也是无 jquery 的 并且它针对快速加载进行了优化 将不胜感激与我分享的任何想法 NONNNNN 如果您不想使用 jQuery 您可以随时尝
  • 正则表达式正在抓取前面的字符

    所以我在正则表达式中遇到了一些不一致的行为 我的正则表达式 lt test 输入字符串 test exe c echo teststring gt test teststring 当我运行这个时https Regex101 com http
  • 自 UTC 时区当天开始以来的秒数

    如何在Python中找到 自UTC时区开始以来的秒数 我查看了文档 但不明白如何使用它datetime timedelta 这是一种方法 from datetime import datetime time utcnow datetime
  • 设置selectedindex不触发onchange事件

    我正在尝试更改选择标签的选定索引 但是通过 jquery 更改索引时不会触发 onchange 事件 我正在动态地为选择标签创建选项 我不会知道选项标签的值 还有其他方法可以实现吗 这是我的代码片段 请随意提供意见 function cal
  • 如何让 Pyflakes 忽略语句?

    我们的许多模块都是从以下开始的 try import json except ImportError from django utils import simplejson as json Python 2 4 fallback 这是整个文
  • 获取 Haskell CSV 中的列并推断列类型

    我正在交互式 ghci 会话中探索 csv 文件 在 jupyter 笔记本中 import Text CSV import Data List import Data Maybe dat lt parseCSVFromFile home
  • 如何从我的应用程序中打开 iPhone 日历?

    我希望能够在我的应用程序中实现一个按钮 用于退出我的应用程序 并将用户带到 iPhone 的日历 我对将用户发送到特定事件不感兴趣 只要打开日历就可以了 有什么建议么 嘿可能是一个迟到的答案 但你现在可以这样做 UIApplication
  • ExtJS 4 关联和 store.save()

    我正在使用 ExtJS 4 并且有一个定义了关联 hasMany 的模型 ModelA gt hasMany gt ModelB 我使用 GridA 显示来自 ModelA 的数据 单击 GridA 中的记录时 我使用 rowSelect
  • 使用jquery进行反应以滑动切换

    我正在尝试通过制作带有可折叠项目的菜单来学习一些 React 我使用 jQuery 来实现它的 SlideToggle 功能 但我无法让它正常工作 反应代码的相关部分是这样的 var CollapsableMenuItem React cr
  • 在react-native-web中使用flex布局复制/粘贴

    我有一个通过 React Native 和 React Native Web 在本机和 Web 上运行的应用程序 一个屏幕包含一个带有自定义项目符号的列表 如下图所示 尽管文本通常会长到多行 问题是 当您复制 粘贴 至少在网络上 时 项目符
  • jquery 承诺的延迟

    我找不到delay or wait函数为jQuery承诺 我在 SO 上找到了一项功能 使用 jQuery Deferred 避免嵌套 setTimeout 回调 https stackoverflow com q 17983331 104