简体   繁体   English

如何正确链接ajax调用?

[英]How do I chain ajax calls properly?

using jQuery 3.2.1 I'm chaining calls to $.ajax like this: 使用jQuery 3.2.1,我将调用链接到$ .ajax,如下所示:

function get(i) {
    return $.ajax(...)
      .done(function() { console.log('get done: ' + i) })
      .fail(function() { console.log('get failed: ' + i) })
}

var p = Promise.resolve();
for (var i = 0; i < len; i++) {
    p = p.then(get(i));
}

p.done(function() { console.log('Finished') });

and I would expect that the ajax call for i=1 would not execute until the call for i=0 had resolved. 并且我希望对i = 1的ajax调用在解决对i = 0的调用之前不会执行。 similarly, the final done() should wait for all the calls to be performed in order 同样,最终的done()应该等待所有调用按顺序执行

in reality I'm seeing 'Finished' before I see anything else and the 'get done' are coming back in random order (the first one finished comes back first is my guess). 实际上,在看到其他内容之前,我已经看到“完成”,并且“完成”以随机顺序返回(我猜第一个完成的首先返回)。

I'm used to Bluebird where this would work. 我已经习惯了蓝鸟在哪里工作。 what am I doing wrong? 我究竟做错了什么?

* Addendum I * *附录一*

to add to the above, I'm loading javascript files that have dependencies and thus need to be loaded in order. 为了补充上述内容,我正在加载具有依赖项的javascript文件,因此需要按顺序加载。 therefore, the first must complete before the second fetch is initiated, otherwise dependencies will fail 因此,第一个必须在启动第二个提取之前完成,否则依赖项将失败

There are two issues: 有两个问题:

  • The get function is executed immediately, while the then method should get a reference to that function for later execution by the Promise implementation. get函数将立即执行,而then方法应获取对该函数的引用,以供Promise实现以后执行。 So replace: 因此,请替换:

     p = p.then(get(i)); 

    with: 与:

     p = p.then(get.bind(null,i)); 
  • JavaScript's native promises do not expose the done method, so replace: JavaScript的本机承诺不会公开done方法,因此请替换:

     p.done(function() { console.log('Finished') }); 

    with: 与:

     p.then(function() { console.log('Finished') }); 

You should probably also add a catch call to the final promise. 你应该还添加了一个catch调用最终承诺。

Corrected version: 更正的版本:

 function get(i) { return $.ajax('https://jsonplaceholder.typicode.com/posts/'+(i+1)) .done(function() { console.log('get done: ' + i) }) .fail(function(err) { console.log('get failed: ' + i) }) } var len = 4; var p = Promise.resolve(); for (var i = 0; i < len; i++) { p = p.then(get.bind(null,i)); } p.then(function() { console.log('Finished') }) .catch(function () { console.log('Error occurred') }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM