Skip to content

Instantly share code, notes, and snippets.

@shama
Created December 5, 2016 17:26
Show Gist options
  • Save shama/24654eab9f6c1ed055b6ebfe776eb10d to your computer and use it in GitHub Desktop.
Save shama/24654eab9f6c1ed055b6ebfe776eb10d to your computer and use it in GitHub Desktop.
I wrap jQuery promises in real promises
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