【问题标题】:jQuery deferreds - order of execution in multiple blocksjQuery deferreds - 多个块中的执行顺序
【发布时间】:2019-08-01 23:00:03
【问题描述】:

注意
这个问题不知何故只发生在特定的服务器端 api 上。因此,它解决了错误的问题。我不会删除它,因为它有答案和 cmets。


我正在尝试执行一些 ajax 请求,在每个完成后做一些事情,在所有事情完成后做一些其他事情,为此我使用下面的代码:

let
        myarr = [],
        myfunc = arg => myarr.push(arg);

$.when(
    $.post(myparams).done(myfunc),
    $.post(otherparams).done(myfunc),
    $.post(yetanother).done(myfunc)

// it comes out with only one arg
).then(e => console.log(myarr));

但是当涉及到执行then块时,它通常只执行了第一个操作的done,我该如何解决这个问题?

如果它是重复的,我很抱歉,但老实说,我什至不知道要搜索什么:/


评论

我还尝试创建自己的延迟,我将在其中执行 ajax 并在 done 块内解析它们,但产生了相同的结果。

仅使用done 或仅使用then,相同。

【问题讨论】:

  • 永远不要使用done,始终使用then
  • @Bergi “永远不要使用done - 为什么这么绝对? thendone 的用例不同。如果您只希望在延迟解决后发生回调怎么办?
  • 仅使用done 或仅使用then 也会发生同样的事情
  • @TylerRoper 我当然在简化。我仍然没有找到done 的用例,其中then 不能很好地工作,并且考虑到done 的陷阱太多,我建议通常避免它。
  • @LucasNoetzold 这是您的确切代码吗?你能提供一个minimal reproducible example吗?

标签: javascript jquery asynchronous es6-promise jquery-deferred


【解决方案1】:

根据 jQuery 在$.when() 上的文档:

每个参数[.then()] 是一个具有以下结构的数组:[ data, statusText, jqXHR ]

意思是你可以做这样的事情......

$.when(
  $.post(myparams),
  $.post(otherparams),
  $.post(yetanother)
).then((res1, res2, res3) => { //Arg for each result
  myfunc(res1[0]);             //Call myfunc for result 1's data
  myfunc(res2[0]);             //Call myfunc for result 2's data
  myfunc(res3[0]);             //Call myfunc for result 3's data
});

虽然也许更干净的版本可能是这样的......

let
  myarr = [],
  myfunc = arg => myarr.push(arg);

$.when(
  $.get('https://jsonplaceholder.typicode.com/todos/1'),
  $.get('https://jsonplaceholder.typicode.com/todos/2'),
  $.get('https://jsonplaceholder.typicode.com/todos/3')
).then((...results) => {                  //Get all results as an array
  results.map(r=>r[0]).forEach(myfunc);   //Call myfunc for each result's data
  console.log(myarr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
猜你喜欢
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多