我可以将native Promise
object传递给jQuery when
并使其表现出预期的效果吗?
答案 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.
$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>
$.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>