• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

jQuery延期 - 向延期合同添加回调

用户头像
it1352
帮助5

问题说明

我正在尝试在其状态设置为成功之前向现有Deferred的合同添加另一个异步调用。而不是尝试用英语解释这个,请参阅以下伪代码:

I'm trying to add another asynchronous call to the contract of an existing Deferred before its state is set to success. Rather than try and explain this in English, see the following pseudo-code:

$.when(
    $.ajax({        
        url: someUrl,
        data: data,
        async: true,        
        success: function (data, textStatus, jqXhr) {
            console.log('Call 1 done.')
            jqXhr.pipe(
                $.ajax({        
                    url: someUrl,
                    data: data,
                    async: true,        
                    success: function (data, textStatus, jqXhr) {
                        console.log('Call 2 done.');
                    },       
                })
            );
        },       
    }),
    $.ajax({        
        url: someUrl,
        data: data,
        async: true,        
        success: function (data, textStatus, jqXhr) {
            console.log('Call 3 done.');
        },       
    })
).then(function(){ console.log('All done!'); });

基本上,呼叫2取决于呼叫1的结果。我希望呼叫1和呼叫3到并行执行。完成所有3个调用后,我希望执行All Done代码。我的理解是 Deferred.pipe()应该将另一个异步调用链接到给定的延迟,但实际上,我总是在完成后完成Call 2。

Basically, Call 2 is dependent on the results of Call 1. I want Call 1 and Call 3 to be executed in parallel. Once all 3 calls are complete, I want the All Done code to execute. My understanding is that Deferred.pipe() is supposed to chain another asynchronous call to the given deferred, but in practice, I always get Call 2 completing after All Done.

有谁知道如何让jQuery延迟做我想做的事情?希望解决方案不会涉及将代码拆分成块。

Does anyone know how to get jQuery's Deferred to do what I want? Hopefully the solution doesn't involve ripping the code apart into chunks any further.

感谢您的帮助。

更新:请参阅我的跟进问题

正确答案

#1

您必须在延迟对象上调用 .pipe 由第一个 $ .ajax 调用返回,而不是在其成功回调中(这根本没有任何效果):

You have to call .pipe on the deferred object returned by the first $.ajax call, not inside its success callback (this does not have any effect at all):

$.when(
    $.ajax({        
        // ...      
    }).pipe(function() {
        // return a deferred object from .pipe
        return $.ajax({        
            // ...      
        });
    }),
    $.ajax({        
        // ...       
    })
).done(function(){ console.log('All done!'); });

.pipe 返回一个新的延迟对象只有两者都得到解决,原始的延期对象和返回的对象得到解决。

.pipe returns a new deferred object which only gets resolved once both, the original deferred object and the returned one get resolved.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcakhje
系列文章
更多 icon
同类精品
更多 icon
继续加载