Created
December 5, 2016 17:26
-
-
Save shama/24654eab9f6c1ed055b6ebfe776eb10d to your computer and use it in GitHub Desktop.
I wrap jQuery promises in real promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fetch (uri) { | |
return new Promise(function (resolve, reject) { | |
$.ajax(uri).then(function (data, textStatus, jqXHR) { | |
resolve([data, textStatus, jqXHR]) | |
}).fail(function (jqXHR, textStatus, errorThrown) { | |
reject([jqXHR, textStatus, errorThrown]) | |
}) | |
}) | |
} | |
// Usage | |
fetch('http://example.com').then(([data, textStatus, jqXHR]) => { | |
// Handle data | |
}).catch(([jqXHR, textStatus, errorThrown]) => { | |
// Handle errorThrown | |
}) | |
// Depending on the app, sometimes I'll make the top level handle the response data / error | |
// That way I don't have to use destructing `([]) => {}` as many promise users expect only | |
// a single value returned in the then() and catch(). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment