简体   繁体   English

是否可以直接通过AJAX创建和使用Deferred对象?

[英]Is it possible to create and use a Deferred object directly with AJAX?

I have an application which sends a few AJAX requests when a user clicks a specific button. 我有一个应用程序,当用户单击特定按钮时,该应用程序会发送一些AJAX请求。

However, I also have something similar to a 'Cancel' button, which should abort all requests. 但是,我还有一个类似于“取消”按钮的东西,该按钮应该中止所有请求。

I'm using $.when currently to handle all of the requests sent, with appropriate callbacks added onto the Promise object it returns. 我正在使用$.when当前处理所有发送的请求,并在返回的Promise对象上添加了适当的回调。

However, the fact that $.when returns a Promise object is frustrating, as it doesn't (deliberately) include the methods Deferred has to control the requests, as shown with this code: 但是, $.when返回Promise对象的事实令人沮丧,因为它没有(故意)包括Deferred必须控制请求的方法,如以下代码所示:

Using $.when 使用$ .when

var x = $.when($.get('/'), $.get('/')); // .then(function() {console.log('done');});

Object.keys(x); 
// ["state", "always", "then", "promise", "pipe", "done", "fail", "progress"]

Using one AJAX request (jqXHR implements the Deferred interface) 使用一个AJAX请求(jqXHR实现Deferred接口)

var x = $.get('/');

Object.keys(x); 
// ["readyState", "getResponseHeader", "getAllResponseHeaders", "setRequestHeader", "overrideMimeType", "statusCode", "abort", "state", "always", "then", "promise", "pipe", "done", "fail", "progress", "complete", "success", "error"]

I'm looking for a way to retrieve the Deferred object, or replace $.when with a method which performs the same, but returns a Deferred object instead. 我正在寻找一种检索Deferred对象的方法,或将$.when替换$.when执行相同功能但返回Deferred对象的方法。 From there, I will be able to call a suitable reject / abort method. 从那里,我将能够调用合适的拒绝/中止方法。

Is this possible? 这可能吗?

You can put the requests into an array and abort them individually when you need to. 您可以将请求放入数组中,并在需要时单独中止它们。

For this you can use .apply on $.when . 为此,您可以在$.when .apply上使用.apply For example: 例如:

var requests = [$.get('/'), $.get('/')];
$.when.apply($,requests).then(function(res1,res2){
      //access results here
});

// aborting:
requests.forEach(function(x){ return x.abort();});

Deferred objects are only used to create promises from callback APIs. 延迟的对象仅用于通过回调API创建承诺。 You can not 'retrieve' the deferred object of an already existing promise. 您不能“检索”已存在的promise的延迟对象。 Only create new ones using it. 仅使用它创建新的。

You might also want to look into Domenic's last() . 您可能还想研究Domenic的last()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM