首页 文章

jquery when():一个vs多个thenables的不同行为

提问于
浏览
0

jQuery.when()可用于在完成可完成对象时执行回调 .

我发现它很有用,因为它可以组合多个可重复的对象:

promise1.then((v1)=>{
  promise2.then((v2)=>{
    promise3.then((v3)=>{
      // arrow pattern ... 
    })         
  })
})

// converts to
$.when(promise1, promise2, promise3)
.done((v1, v2, v3)=>{
  // yay, nice and flat
});

但是现在我发现当我提供一个vs多个thenable时,函数的行为会有所不同 . 在多个井的情况下, when() 似乎记录了附加信息,实际返回可通过 v1[0] 访问 .

我设置了一个小提琴:https://jsfiddle.net/xpvt214o/989940/

HTML:

<ul>
<li><div id="result1"></div></li>
<br>
<li><div id="result2"></div></li>
</ul>

JS:

$.when(
    $.get("https://httpbin.org/get")
).done((v1)=>[
  $("#result1").html(v1["url"])
])

$.when(
    $.get("https://httpbin.org/get"),
    $.get("https://httpbin.org/get")
).done((v1, v2)=>[
  $("#result2").html(v1[0]["url"])
])

2 回答

  • 1

    这有点怪癖 $.ajax.then() 有多个参数, $.when 只有在传递多个promise时才会返回所有参数

    一种解决方法是为每个请求添加 then()

    $.when(
        $.get("https://httpbin.org/get").then(d=>d),
        $.get("https://httpbin.org/get").then(d=>d)
    ).then((v1, v2)=>{
      console.log(v1["url"])
    })
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    

    或者使用 Promise.all() 忽略 $.ajax.then() 的辅助参数

    Promise.all([$.get("https://httpbin.org/get"), $.get("https://httpbin.org/get")])
      .then(res => console.log(res[0].url))
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
  • 0

    我无法找到任何文档告诉我为什么在多个案例中将结果转换为3-ary数组,而不是单个案例 .

    由于您的帖子可疑地没有实际问题,我假设您只是想强制两个调用以相同的方式运行?您可以通过在单调用案例中将null-promise作为虚拟第二个参数传递来实现此目的:

    $.when(
        $.get("https://httpbin.org/get"),
        null
    ).done((v1)=>[
      $("#result0").html(JSON.stringify(v1))
    ])
    

    这将使JQuery对结果使用与多案例相同的数组表示法

    $.when(
        $.get("https://httpbin.org/get"),
        $.get("https://jsonplaceholder.typicode.com/todos/1")
    ).done((v1,v2)=>{
      $("#result1").html(JSON.stringify(v1))
      $("#result2").html(JSON.stringify(v2))
    })
    

    小提琴:https://jsfiddle.net/xpvt214o/990023/

相关问题