使用延迟到多个ajax调用的链循环

时间:2022-08-23 11:12:15

There are multiple questions that already have an answer about this, but all aren't working so far it this kind of setup.

有很多问题已经对此有了答案,但到目前为止所有这些都没有用到这种设置。

function login(u,p) {
   console.log(1);
   return $.post(url, {u,p});
}

function out() {
   console.log(3);
   //a function that does not return deferred
   // clear cookies
}

function doSomething() {
  console.log(2);
  // a function that returns a deferred
  return $.post(...);
}
var data = [{u: 'au', p: 'ap'}, {u: 'bu', p: 'bp'}]

$.each(data, function(k,v){
  login(v.u, v.p).then(doSomething).then(out);
});

I was expecting it's sequence to be like:

我期待它的顺序如下:

1
2
3
1
2
3

But I get

但我明白了

1
2
1
3
2
3

Why is it like that, even though I am waiting for the promise to be resolve using then

为什么会这样,即使我在等待使用当时的解决方案

2 个解决方案

#1


2  

If you want the logins to run synchronously:

如果您希望登录同步运行:

var p = new jQuery.Deferred();
$.each(data, function(k,v){
  p.then(function() {
    return login(v.u, v.p);
  }).then(doSomething).then(out);
});

Each new item iterated over in $.each won't trigger a new response until p finishes the last one.

在$ .each中迭代的每个新项目都不会触发新的响应,直到p完成最后一个。

#2


1  

The idea is to create a recursive function like @Popnoodles have mentioned.

这个想法是创建一个像@Popnoodles所提到的递归函数。

e.g.

function a() {
  return $.post();
}

function b() {
  return $.post();
}

function c() {
   console.log('no promise.');
}

// and the recursive main function

function main() {
   if(counter < data.length){
      $.when(a().then(b).then(c)).done(function(){
        counter++;
        main();
      });
   }
}

main();

Here is how it works, open the console to see how it logs the function in sequence.

以下是它的工作原理,打开控制台,看看它是如何按顺序记录功能的。

#1


2  

If you want the logins to run synchronously:

如果您希望登录同步运行:

var p = new jQuery.Deferred();
$.each(data, function(k,v){
  p.then(function() {
    return login(v.u, v.p);
  }).then(doSomething).then(out);
});

Each new item iterated over in $.each won't trigger a new response until p finishes the last one.

在$ .each中迭代的每个新项目都不会触发新的响应,直到p完成最后一个。

#2


1  

The idea is to create a recursive function like @Popnoodles have mentioned.

这个想法是创建一个像@Popnoodles所提到的递归函数。

e.g.

function a() {
  return $.post();
}

function b() {
  return $.post();
}

function c() {
   console.log('no promise.');
}

// and the recursive main function

function main() {
   if(counter < data.length){
      $.when(a().then(b).then(c)).done(function(){
        counter++;
        main();
      });
   }
}

main();

Here is how it works, open the console to see how it logs the function in sequence.

以下是它的工作原理,打开控制台,看看它是如何按顺序记录功能的。