标签: jquery-deferred

jQuery 延迟 - 捕获与失败

我想确保我没有错过任何一个技巧;在 Kris Kowal 的库中,您可以执行以下操作作为 Promise 中的通用 catch 语句:

var a, b, c, d, e, f;

readFile('fileA')
    .then(function (res) {
        a = res;

        return readFile('fileB');
    })
    .then(function (res) {
        b = res;

        return readFile('fileC');
    })
    .then(function (res) {
        c = res;

        return readFile('fileD');
    })
    .then(function (res) {
        d = res;

        return readFile('fileE');
    })
    .then(function (res) {
        e = res;

        return readFile('fileF');
    })
    .then(function () {
        f = res;
    })
    .catch(function () {
        // error happened in file read *somewhere* (don't care …
Run Code Online (Sandbox Code Playgroud)

javascript jquery promise deferred jquery-deferred

5
推荐指数
1
解决办法
5848
查看次数

我可以将 Promise 传递给 jQuery.when(),还是只传递给 Deferreds?

jQuery.when()的文档说这个函数需要延迟。但是,它稍后还说:

如果将单个参数传递给 jQuery.when() 并且它不是 Deferred 或 Promise ...

这似乎意味着它也可以采用 Promises。但是 Promises 不是 Deferreds——它们有一个 Deferred 方法的子集。我猜你可以说 Deferred 是 Promise,但 Promise 不是 Deferred。

问题:

  1. $.when() 可以接受 Promises 或 Deferreds 吗?这似乎在我的测试中有效。
  2. 文档中是否有错误?我认为应该说 $.when() 需要 Promises,而不仅仅是 Deferreds。

javascript jquery parameter-passing jquery-deferred .when

5
推荐指数
1
解决办法
827
查看次数

我如何使用jQuery.Deferred对象等待异步函数调用完成?

我在表单中使用Plupload文件上传器.我想自定义它,以便在提交表单时,即单击"提交"按钮时,首先发生的是文件上载,然后是表单的提交.

据我所知,我可能错了,但似乎调用uploader.start()是异步函数调用.因此,目前,上传将开始,表单将在文件上传之前提交.问题是我无法控制这个函数调用.

我最近读到了关于jQuery 1.5新版本和新的Deferred Object,看起来这有可能帮助我解决这个问题.有没有办法等待异步函数调用完成其工作,然后在调用后继续执行代码.所以我正在寻找类似下面的伪代码...

var uploader = $('#plupload_container').pluploadQueue();

$('#submitButton').click(function() {

   // if there are files to be uploaded, do it
   if (uploader.files.length > 0) {

      // make the call and wait for the uploader to finish
      uploader.start();
      while ( the uploading is not done ) {
         wait for the uploader to finish
      }

      // continue with submission
   }
});
Run Code Online (Sandbox Code Playgroud)

有没有办法"等待" uploader.start()完成,基本上在click事件处理程序上暂停,以便可以先上载所有文件,然后其余的click事件处理程序可以完成执行?我尝试了以下内容,但在文件上传之前打印了"完成"...

$.when(uploader.start()).then(function () {
   console.log("done")
});
Run Code Online (Sandbox Code Playgroud)

另一个有用的信息...我可以将某些事件绑定到此uploader …

ajax jquery plupload jquery-deferred

4
推荐指数
1
解决办法
6816
查看次数

如果有多个动画元素,如何知道jquery效果何时结束

给出以下示例:如果<li>找到5个元素,则回调将触发警报5次 ...

有没有一种简单的方法可以找出动画何时真正结束并且只需点燃一次

$(this).parent().siblings('li').slideUp(500,function(){
    alert 
});
Run Code Online (Sandbox Code Playgroud)

javascript jquery callback jquery-deferred jquery-animate

4
推荐指数
1
解决办法
207
查看次数

将$ .when()/ $ .promise()与包含AJAX的函数一起使用

在这个问题上真的很难,而且我知道$.when()可以这样使用(有多个AJAX语句)来保证你完成它们的时候.

http://jsfiddle.net/M93MQ/

    $.when(
        $.ajax({ url: '/echo/html/', success: function(data) {
            alert('request 1 complete')
          }
        }),

        $.ajax({ url: '/echo/html/', success: function(data) {
            alert('request 2 complete')
          }
        })
    ).then( function () { alert('all complete'); });
Run Code Online (Sandbox Code Playgroud)

但这只适用于raw $.ajax(),无论如何都有与函数调用相同的功能,反过来它们内部的ajax(以及其他随机逻辑)?

伪代码的想法:

    // The functions having the AJAX inside them of course
    $.when(ajaxFunctionOne, ajaxFunctionTwo).then(function () {
        alert('all complete'); 
    });
Run Code Online (Sandbox Code Playgroud)

javascript ajax jquery jquery-deferred

4
推荐指数
1
解决办法
612
查看次数

jQuery Deferred - 等待动态异步请求完成所有操作,即使有些失败也是如此

我得到了一个动态异步请求(对于jsfiddle,我使用了ajax),无论成功与否,我都需要等待,这意味着即使某些请求失败,我也只需要知道所有进程都已完成.

//动态:在我的情况下,这是由ajax请求产生的,因此后续异步请求的数量是灵活的

所以我最初使用这段代码:

    $.when.apply($,deferreds).done(function() {
        $("div").append("<p>All done!</p>");
    }).fail(function(){
        $("div").append("<p>Something failed!</p>");
    });
Run Code Online (Sandbox Code Playgroud)

但是在其中一个延迟失败的情况下,将立即调用失败回调.我尝试将其更改为always(),但结果是:

未捕获的TypeError:对象#没有方法'总是'

那么如何为此实现always()类型的解决方案呢?

小提琴

我的原始资料来源:jQuery Deferred - 等待多个AJAX请求完成

jquery asynchronous jquery-deferred

4
推荐指数
1
解决办法
3214
查看次数

JavaScript Promise陷入僵局

我有一个异步功能,我做了多次(2),但由于某种原因,承诺陷入决心.它执行resolve(),但不执行任何操作.

这是函数(基本上是从URL创建一个blob):

function getBlobAt(url, callback) {
console.log("New getBlobAt Call");
return new Promise(function(resolve) {
    console.log("getBlobAt Promise Created");
    window.URL = window.URL || window.webkitURL;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
        console.log("getBlobAt promise completed, resolving...");
        var burl = window.URL.createObjectURL(this.response);
        console.log("getBlobAt promise completed, resolving2...");
        resolve(burl);
        console.log("getBlobAt promise completed, resolving3...");
        //window.URL.revokeObjectURL(burl); //DO THIS WHEN LOADING NEW SONG
    };
    console.log("getBlobAt xhr.send() and callback");
    xhr.send();
    callback(xhr);
    //return xhr;
});
}
Run Code Online (Sandbox Code Playgroud)

这是任务图:

            var taskstrings = [endmp3, albumart];
            var getBlobTasks …
Run Code Online (Sandbox Code Playgroud)

javascript jquery resolve promise jquery-deferred

4
推荐指数
1
解决办法
1275
查看次数

jQuery:按顺序执行函数数组(延迟和非延迟)

我使用Promises相当新,并且很难绕过jQuery deferreds.

我目前拥有的是一系列我在某一点执行的函数:

while (queue.length) {
    (queue.shift())();   
}
Run Code Online (Sandbox Code Playgroud)

这个问题是,其中一些函数是异步的,但我需要它们一个接一个地运行.

所以队列中的一些函数返回一个延迟(例如通过jQuery.ajax()),有些只是普通的函数.我想知道如何按顺序+顺序执行它们(仅在前一个函数完成时才执行下一个函数).

我想也许jQuery.when会是我想要的,但我无法弄清楚它是如何完全的,我只是来了这个:

var deferred = jQuery.Deferred();
    while (queue.length > 0) {
       deferred.done().then(queue.shift());
    }
Run Code Online (Sandbox Code Playgroud)

jquery promise jquery-deferred

4
推荐指数
1
解决办法
5895
查看次数

使用虚拟和空jQuery承诺

我使用jQuery运行多个动画并在完成后执行一些操作promises:

$.when(foo(),  
       bar(),  
       baz())  
 .done(allDone);  
Run Code Online (Sandbox Code Playgroud)

每个函数(foo等)返回一个jQuery.Promise().

现在说我想要包含一个不动画任何东西的函数,但它的时间与动画有关 - 我不能将它包含在链中,因为它不会返回一个承诺.

所以我可以像这样破解它:

function qux() {
  if (something) {
    return $(".whatever")
      .removeClass("bob")
      .addClass("fred")
      .append(/*...do stuff...*/)
      .animate({ left: "+=0" }, 0, callback ) // <-- dummy animation does nothing
      .promise();                             // <-- this is a dummy promise
  }
  else {
    return $().promise();                     // <-- this is an "empty" promise
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我可以链接它:

$.when(foo(),  
       bar(),  
       baz(),
       qux())  
 .done(allDone);  
Run Code Online (Sandbox Code Playgroud)

这有效.但是我在这里弯曲规则 - 有没有我没有考虑到的问题,或者我在某种程度上踩到了fx队列?

更新
根据以下答案,该qux()功能可以重写为:

function qux() { …
Run Code Online (Sandbox Code Playgroud)

javascript jquery promise jquery-deferred

4
推荐指数
1
解决办法
5734
查看次数

jQuery.Deferred异常:字符串与预期的模式不匹配

我对于这个控制台错误有点头疼,仅在Safari上才可以(实际上是在MacBook上工作)。

我有这个功能:

function exists(element){
    var exists = document.querySelector(element);
    return exists;
}
Run Code Online (Sandbox Code Playgroud)

在另一个函数内部调用:

function includeHoverStylesheet(){
    var path = $("body").attr("data-hover");
    if (!("ontouchstart" in document.documentElement || exists("link[href='" + path + "'"))) {
        var link = document.createElement("link");
        link.rel = "stylesheet", link.href = path, document.head.appendChild(link) && document.body.removeAttribute("data-hover");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在Chrome上像超级按钮一样工作,但是在Safari上,控制台会抛出此错误:

1) Invalid CSS property declaration at: *
2) jQuery.Deferred exception: The string did not match the expected pattern.
3) SyntaxError (DOM Exception 12): The string did not match the expected pattern.
Run Code Online (Sandbox Code Playgroud)

有人知道发生了什么事吗???

在此先感谢大家!

safari syntax-error jquery-deferred safari-web-inspector jquery-3

4
推荐指数
1
解决办法
7057
查看次数