Last active
August 29, 2015 14:06
-
-
Save Naddiseo/23d6fd726467a055e927 to your computer and use it in GitHub Desktop.
ES6 Promise version of Mithril's request function
This file contains hidden or 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
m.request = function(xhrOptions) { | |
var deferred = m.deferred() | |
var serialize = xhrOptions.serialize = xhrOptions.serialize || JSON.stringify | |
var deserialize = xhrOptions.deserialize = xhrOptions.deserialize || JSON.parse | |
var extract = xhrOptions.extract || function(xhr) { | |
return xhr.responseText.length === 0 && deserialize === JSON.parse ? null : xhr.responseText | |
} | |
xhrOptions.onload = xhrOptions.onerror = function(e) { | |
e = e || event | |
var unwrap = (e.type == "load" ? xhrOptions.unwrapSuccess : xhrOptions.unwrapError) || identity | |
try { | |
var response = unwrap(deserialize(extract(e.target, xhrOptions))) | |
if (e.type == "load") { | |
if (type.call(response) == "[object Array]" && xhrOptions.type) { | |
for (var i = 0; i < response.length; i++) response[i] = new xhrOptions.type(response[i]) | |
} | |
else if (xhrOptions.type) response = new xhrOptions.type(response) | |
deferred.resolve(response); | |
} | |
else deferred.reject(response); | |
} | |
catch (e) { | |
// Any exception in the onerror/onload is not part of the promise, so it should still throw to the caller | |
if (e instanceof SyntaxError) throw new SyntaxError("Could not parse HTTP response. See http://lhorie.github.io/mithril/mithril.request.html#using-variable-data-formats") | |
else throw e | |
} | |
finally { | |
// I'm assuming you always want there to be an endcomputation so I'm sticking in this finally. | |
if (xhrOptions.background !== true) m.endComputation() | |
} | |
} | |
// Put a try/catch around anything that can potentially throw on function execution. | |
try { | |
if (xhrOptions.background !== true) m.startComputation() | |
xhrOptions.url = parameterizeUrl(xhrOptions.url, xhrOptions.data) | |
xhrOptions = bindData(xhrOptions, xhrOptions.data, serialize) | |
ajax(xhrOptions) | |
} | |
catch (e) { | |
// An exception in the promise's body should call the first rejection handler | |
deferred.reject(e); | |
} | |
return deferred.promise | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment