jQuery.when是否接受本地Promise对象?

时间:2018-07-21 19:19:08

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

我可以将native Promise object传递给jQuery when并使其表现出预期的效果吗?

2 个答案:

答案 0 :(得分:2)

是的,确实如此。传递给then的第一个参数是Promise,从那里我们必须再次调用result.then()以获得Promise的结果。

$.when(new Promise(resolve => {
  setTimeout(() => resolve('abc123'), 2000)
})).then(result => result.then(data => console.log(data)))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

Yes or no depending on which version of jQuery is used.

  1. jQuery <3 ... no ... $when() will not unwrap a native js Promise. It treats anything other than its own Deferreds/Promises in the same way it would treat any other object/value.

// using jQuery 2.1.1
$.when(Promise.resolve('xxxyyy')).then(result => {
    console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  1. jQuery 3+ ... yes ... at version 3, jQuery was revised to be (at least in this regard) compliant with the Promise/A+ spec. $.when() will unwrap any Promise/A+ compatible promise/thenable, including js native Promises.

// using jQuery 3.1.1
$.when(Promise.resolve('xxxyyy')).then(result => {
    console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>