编程语言
首页 > 编程语言> > javascript – jQuery Deferred and Promise用于顺序执行同步和异步函数

javascript – jQuery Deferred and Promise用于顺序执行同步和异步函数

作者:互联网

如果我想以特定的顺序执行同步和异步函数,我可以使用jQuery promise,但它看起来并不像我期望的那样工作.

函数a,b和c应该在调用deferred.resolve()时以该顺序执行我希望函数b被执行但是无论是否调用了resolve,所有函数都会立即执行.

这是代码:

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

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

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

但是所有具有相同意外结果的b都会在延迟a被解析之前被调用,c被调用之前被调用b.

解决方法:

对于1.8之前的jQuery,这是一个问题,但对于新版本的jQuery,这不再是一个问题:

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();

DEMO

下面是jQuery 1.7.2的演示

DEMO

标签:javascript,jquery,asynchronous,promise,synchronous
来源: https://codeday.me/bug/20190930/1836132.html