jQuery:在本地上下文中正确使用deferred(即没有AJAX)

jQuery: using deferred properly in a local context (ie. no AJAX)

本文关键字:deferred AJAX 上下文 jQuery      更新时间:2023-09-26

为我确信的转发道歉;我真的非常广泛地寻找我的问题的答案(我也理解)。

我试图学习的是任意链接函数,使它们必须在下一个函数发生之前完成,据我所知,这就是jQuery的deferred()的目的。所以在下面的代码中,我想象应该发生的是:

  1. 执行包含在负载延迟对象内的函数;之后
  2. 执行then()中包含的函数;之后
  3. 执行done()中包含的函数

宇宙中的每个教程都在$.when()之后使用一个$.ajax()对象,如果只想控制本地上下文中的执行序列,那么这是无用的。

以下是我一直在尝试的:

var preloadDone = false,
var testDone = false,
var load = $.deferred(function() {
                //cacheImages() is a plugin, works fine
                $("img.image-loader.preload").cacheImages();
                preloadDone = true;
            });
var loader = $.when(load)
        .then(function() {
        if (preloadDone) {
            console.log("then called in sequence");
        } else {
            console.log("then called out of sequence"); // wrong order, every time
        }
        XBS.cache.cbDone = true;
}).done(function() {
        if (XBS.cache.cbDone) {
            console.log("even done was called in right sequence!"); // proper order, every time
        } else {
            console.log("done() wasn't called in order.."); 
        }
});
load.resolve(); // nothing happens
// load();  also tried this; nothing happens

据我所知,这与jQuery$.when()文档中给出的示例完全相同。Lil帮忙?

这里有一个演示如何一个接一个地运行许多函数,但只能在每个函数完成后运行。这是通过使用异步函数来实现的。

Demo(一个接一个地运行3个函数。如果我有警报("starting*"),那就是你想把你想做的工作放在已完成的函数中,你就包括了你想运行的下一个函数。)

http://jsfiddle.net/5xLbk91c/

//the Assync function. Pause is the time in miliseconds to pause between loops
var asyncFor = function(params) {
    var defaults = {
      total: 0,
      limit: 1,
      pause: 10,
      context: this
    },
      options = $.extend(defaults, params),
      def = $.Deferred(),
      step = 0,
      done = 0;
    this.loop = function() {
      if (done < options.total) {
        step = 0;
        for (; step < options.limit; step += 1, done += 1) {
          def.notifyWith(options.context, [done]);
        }
        setTimeout.apply(this, [this.loop, options.pause]);
      } else {
        def.resolveWith(options.context);
      }
    };
    setTimeout.apply(this, [this.loop, options.pause]);
    return def;
  };


function one() {
asyncFor({
  total: 1,  // run only once. If you want to loop then increase to desired total. 
  context: this
}).progress(function(step) {
alert("starting one")
}).done(function() {
alert("finished one")
two()
});    
}
function two() {
asyncFor({
  total: 1,
  context: this
}).progress(function(step) {
alert("starting two")
}).done(function() {
alert("finished two")
three()
});    
}
function three() {
asyncFor({
  total: 1,
  context: this
}).progress(function(step) {
alert("starting three")
}).done(function() {
alert("finished three and all done")
});    
}

您可能希望通过更改代码来开始调查

var load = function() {
  var deferred = $.Deferred();
  $("img.image-loader.preload").cacheImages();
  preloadDone = true;
  return deferred;
};

还请注意,您可以将一系列承诺传递给$.when().

向致以最良好的问候