I have written a parser function that returns a JQuery Promise. You can see from the code that this is the top level parser and it delegates out to two other more specific parsers.
At the minute it feels a little scattered about with the promise being rejected and resolved all over the place. perhaps it would be better with a try and catch and an error handler that rejected the promsie? how would others approach this?
/**
* Inspects JSON and delegates to either the sourceParser or the dataParser.
*
* @constructor
* @param {Object} json
*
* @returns JQuery Promsise
* done: -
* fail: error message
* progress: Progress message
*/
function Parser(json)
{
var dfd = $.Deferred();
dfd.notify("Parsing");
if (json && typeof json === "object")
{
if (json.hasOwnProperty("GetDataSources"))
{
var dataSource = json.GetDataSources;
if (this.isSuccessfulResponse(dataSource.Response))
{
// Notify the caller of any progress
dfd.notify("Parsing Source");
// Create a new Source Parser
var sourceParser = new SourceParser(dataSource);
sourceParser.done(dfd.resolve);
sourceParser.fail(dfd.reject);
}
else
{
dfd.reject("Parsing Source Failed");
}
}
else if (json.hasOwnProperty("GetData"))
{
var data = json.GetData;
if (this.isSuccessfulResponse(data.Response))
{
// Notify the caller of any progress
dfd.notify("Parsing Data");
// Create a new Data Parser
var dataParser = new DataParser(data);
dataParser.done(dfd.resolve);
dataParser.fail(dfd.reject);
}
else
{
// Pass back an error message?
dfd.reject("Parsing Data Failed");
}
}
}
else
{
dfd.reject("There was a problem reading the JSON")
}
return dfd.promise();
}