Can I pass a native Promise
object to jQuery when
and have it behave as expected?
Asked
Active
Viewed 360 times
1

Chris W.
- 37,583
- 36
- 99
- 136
-
1Possible duplicate of [Can I pass Promises to jQuery.when(), or only Deferreds?](https://stackoverflow.com/questions/36434557/can-i-pass-promises-to-jquery-when-or-only-deferreds) – bigless Jul 21 '18 at 19:47
-
If you have native promises, then we'd recommend you use `Promise.all()` since it is generally much easier to use. – jfriend00 Jul 21 '18 at 21:17
-
@jfriend00 were integrating a legacy codebase which uses jquery deferreds / when with newer ES6 codebase, so we need to use both. – Chris W. Jul 25 '18 at 22:49
-
@bigless the question certainly is worded like a duplicate, but i have a very hard time parsing the answer to that question. There are many "promises" referenced and its very unclear what version of Jquery they are talking about and what kind of promises they are talking about. – Chris W. Jul 25 '18 at 22:50
2 Answers
4
Yes or no depending on which version of jQuery is used.
- 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>
- 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>

Roamer-1888
- 19,138
- 5
- 33
- 44
2
Yes, it does. The first parameter passed to the then
is the promise, from there we have to call result.then()
again to get the result of the 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>

Get Off My Lawn
- 34,175
- 38
- 176
- 338