jQuery的递延并承诺同步和异步funcitons的顺序执行 [英] jQuery Deferred and Promise for sequential execution of synchronous and asynchronous funcitons

查看:218
本文介绍了jQuery的递延并承诺同步和异步funcitons的顺序执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想有同步和异步功能,以特定的顺序,我可以使用jQuery的承诺,但它似乎没有工作,我希望它的工作方式执行。

If I want to have synchronous and asynchronous functions execute in a particular order I could use jQuery promise but it doesn't seem to work the way I'd expect it to work.

功能A,B和C应按上述顺序在该 deferred.resolve()叫我期望被执行函数B,但所有的功能,当执行将立即执行不管决心之称。

Functions a,b and c should execute in that order when in a the deferred.resolve() is called I'd expect function b to be executed but all functions are executed immediately no matter if the resolve is called.

下面是code:

function a(){
  var deferred = $.Deferred();
  setTimeout(function(){
    console.log("status in a:",deferred.state());
    //this should trigger calling a or not?
    deferred.resolve("from a");
  },200);
  console.log("a");
  return deferred.promise();
};
function b(){
  var deferred = $.Deferred();
  setTimeout(function(){
    console.log("status in b:",deferred.state());
    deferred.resolve("from b");
  },200);
  console.log("b");
  return deferred.promise();
}
//synchronous function
function c(){
  var deferred = $.Deferred();
  console.log("c");
  console.log("status in c:",deferred.state());
  deferred.resolve("from c");
  return deferred.promise();
}
function test(){
  fn=[a,b,c],i=-1,
  len = fn.length,d,
  d = jQuery.Deferred(),
  p=d.promise();
  while(++i<len){
    p=p.then(fn[i]);
  }
  p.then(function(){
    console.log("done");
  },
  function(){
    console.log("Failed");
  });
  d.resolve();
  //instead of the loop doing the following has the same output
  //p.then(a).then(b).then(c);
  //d.resolve();
}
test();

输出是:

a
b
status in c: pending
c
done
status in a: pending
status in b: pending

期望的输出:

a
status in a: pending
b
status in b: pending
c
status in c: pending
done

尝试了以下一些修改的组合:

Tried a some combinations of the following modifications:

  d = jQuery.Deferred();
  setTimeout(function(){d.resolve();},100);
  var p=d.promise();
  while(++i<len){
    p.then(fn[i]);
  }

但都同样意想不到的结果,推迟的前B获得所谓的解决,C叫作延期之前的B得到解决。

But all with same unexpected results, b gets called before deferred of a is resolved, c is called before deferred of b is resolved.

推荐答案

有关的jQuery之前1.8,这是一个问题,但对jQuery的新版本中,这是不是一个问题了:

For jQuery prior to 1.8, this is a problem, but for new versions of jQuery, this is not a problem anymore:

function test(){
  var d = jQuery.Deferred(), 
  p=d.promise();
  //You can chain jQuery promises using .then
  p.then(a).then(b).then(c);
  d.resolve();
}
test();

演示

下面的jQuery 1.7.2的演示

Below is the demo of jQuery 1.7.2

演示

这篇关于jQuery的递延并承诺同步和异步funcitons的顺序执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆