Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 逐一履行承诺_Javascript_Jquery - Fatal编程技术网

Javascript 逐一履行承诺

Javascript 逐一履行承诺,javascript,jquery,Javascript,Jquery,我有一个测试函数需要按顺序执行,即;第一个电话,第二个电话,第三个电话 电流输出:- started == first_call VM81:49 status in : first_call pending VM81:47 started == second_Call VM81:47 started == third_Call VM81:49 status in : second_Call pending VM81:49 status in : third_Call pending f

我有一个测试函数需要按顺序执行,即;第一个电话,第二个电话,第三个电话

电流输出:-

started == first_call
VM81:49 status in : first_call  pending
VM81:47 started == second_Call
VM81:47 started == third_Call
VM81:49 status in : second_Call  pending
VM81:49 status in : third_Call  pending


function test_func(call_from){
  var deferred = $.Deferred();
    console.log('started ==',call_from)
  setTimeout(function(){
    console.log("status in :",call_from + '  ' +  deferred.state());
    deferred.resolve();
  },5000);

  return deferred.promise();
};
test_func('first_call').then(function(){
    test_func('second_Call')
  }).then(function(){
    test_func('third_Call')
  })

确保将每个
承诺
返回
一起发送到
承诺链的下游,如:

test_func('first_call')
  .then(function(){
    return test_func('second_Call');
  })
  .then(function(){
    return test_func('third_Call');
  })
  .then(function() {
     console.log('done');
   });
请参阅更新的js fiddle以证明这一点:


此外,如果您不
返回
承诺
,链中的每个项目将并行运行(抵消一点时间),而不是按顺序运行。通过返回它们,您通知JavaScript您希望“等待”完成
承诺,从而允许
然后
的链正常工作。

这里可能是您的答案第一个
的可能重复。然后
回调需要
返回test\u func(“第二次调用”)
我可以建议异步吗?这是一个库,它提供了许多函数,帮助您解决异步编程带来的控制流和其他难题?