Skip to content

Instantly share code, notes, and snippets.

@ranwahle
Last active September 9, 2015 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranwahle/2d38730af21909dd70a2 to your computer and use it in GitHub Desktop.
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
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