jQuery1.5带来了新的延迟对象和附带的方法.when.Deferred._Deferred.

对于那些以前没有使用过.Deferred的人,我已经对source for it进行了注释.

这些新方法的可能用途是什么?我们如何着手将它们融入模式?

我已经读过APIsource,所以我知道它的作用.我的问题是,我们如何在日常代码中使用这些新功能?

我有一个简单的example个缓冲区类,它按顺序调用Ajax请求.(下一个在前一个结束后开始).

/* Class: Buffer
 *  methods: append
 *
 *  Constructor: takes a function which will be the task handler to be called
 *
 *  .append appends a task to the buffer. Buffer will only call a task when the 
 *  previous task has finished
 */
var Buffer = function(handler) {
    var tasks = [];
    // empty resolved deferred object
    var deferred = $.when();

    // handle the next object
    function handleNextTask() {
        // if the current deferred task has resolved and there are more tasks
        if (deferred.isResolved() && tasks.length > 0) {
            // grab a task
            var task = tasks.shift();
            // set the deferred to be deferred returned from the handler
            deferred = handler(task);
            // if its not a deferred object then set it to be an empty deferred object
            if (!(deferred && deferred.promise)) {
                deferred = $.when();
            }
            // if we have tasks left then handle the next one when the current one 
            // is done.
            if (tasks.length > 0) {
                deferred.done(handleNextTask);
            }
        }
    }

    // appends a task.
    this.append = function(task) {
        // add to the array
        tasks.push(task);
        // handle the next task
        handleNextTask();
    };
};

我正在寻找.Deferred.when的演示和可能的用法.

看到._Deferred个这样的例子也会很高兴.

例如,链接到新的jQuery.ajax源代码就是作弊.

我特别感兴趣的是,当我们抽象出一个操作是同步还是异步完成时,有哪些技术可用.

推荐答案

我能想到的最佳用例是缓存AJAX响应.下面是一个修改后的Rebecca Murphey's intro post on the topic例:

var cache = {};

function getData( val ){

    // return either the cached value or jqXHR object wrapped Promise
    return $.when(
        cache[ val ] || 
        $.ajax('/foo/', {
            data: { value: val },
            dataType: 'json',
            success: function( resp ){
                cache[ val ] = resp;
            }
        })
    );
}

getData('foo').then(function(resp){
    // do something with the response, which may
    // or may not have been retrieved using an
    // XHR request.
});

基本上,如果该值在从缓存中立即返回之前已经被请求过一次.否则,AJAX请求将获取数据并将其添加到缓存中.$.when/.then不在乎这些;您需要关心的只是使用响应,在这两种情况下,响应都会传递给.then()处理程序.jQuery.when()将未promise /延期处理为已完成的promise ,立即执行链上的任何.done().then().

延迟适用于任务可能异步运行,也可能不异步运行,并且希望从代码中抽象出该条件的情况.

另一个使用$.when助手的真实示例:

$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {

    $(tmpl) // create a jQuery object out of the template
    .tmpl(data) // compile it
    .appendTo("#target"); // insert it into the DOM

});

Javascript相关问答推荐

React Native平面列表自动滚动

获取加载失败:获取[.]添加时try 将文档添加到Firerestore,Nuxt 3

从PWA中的内部存储读取文件

Phaser 3 console. log()特定游戏角色的瓷砖属性

在Vite React库中添加子模块路径

引用在HTMLAttributes<;HTMLDivElement>;中不可用

使用LocaleCompare()进行排序时,首先使用大写字母

VUE 3捕获错误并呈现另一个组件

在浏览器中触发插入事件时检索编码值的能力

以Angular 实现ng-Circle-Progress时出错:模块没有导出的成员

有条件重定向到移动子域

在Matter.js中添加从点A到另一个约束的约束

如何在Svelte中从一个codec函数中调用error()?

使用Nuxt Apollo在Piniastore 中获取产品细节

如何在TransformControls模式下只保留箭头进行翻译?

需要RTK-在ReactJS中查询多个组件的Mutations 数据

Django模板中未加载JavaScript函数

使用Library chart.js在一个带有两个y轴的图表中绘制两个数据集

如何检测当前是否没有按下键盘上的键?

如何向内部有文本输入字段的HTML表添加行?