Last active
September 9, 2015 11:33
-
-
Save ranwahle/2d38730af21909dd70a2 to your computer and use it in GitHub Desktop.
JSON-tryparse parses JSON (using JSON.parse) and returns promise to handle success / error of parsing
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
if (!JSON.tryParse) | |
{ | |
JSON.tryParse = function (str) { | |
var successState=1, errorState = 2, result, errorResult, | |
promise = { | |
then: function(successCallback, errorCallback) | |
{ | |
if (this.state === successState) | |
{ | |
if (successCallback) | |
successCallback(this.result); | |
} | |
else if (errorCallback) | |
{ | |
errorCallback(this.errorResult); | |
} | |
return this; | |
}, | |
done: function(callback) | |
{ | |
callback(); | |
return this; | |
} | |
} | |
try { | |
promise.result = JSON.parse(str); | |
promise.state = successState; | |
} | |
catch (err) { | |
promise.state = errorState; | |
promise.errorResult = err; | |
} | |
return promise; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment