Skip to content

Commit

Permalink
refactor: simplify compileAsync, #249
Browse files Browse the repository at this point in the history
  • Loading branch information
epoberezkin committed Oct 20, 2016
1 parent 3fab5c7 commit 48cee59
Showing 1 changed file with 15 additions and 30 deletions.
45 changes: 15 additions & 30 deletions lib/compile/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,13 @@ function compileAsync(schema, callback) {
/* jshint validthis: true */
var schemaObj;
var self = this;
var p;
try {
schemaObj = this._addSchema(schema);
} catch(e) {
p = Promise.reject(e);
}
if (typeof this._opts.loadSchema != 'function')
throw new Error('options.loadSchema should be a function');

if (!p) {
if (schemaObj.validate) {
p = Promise.resolve(schemaObj.validate);
} else {
if (typeof this._opts.loadSchema != 'function')
throw new Error('options.loadSchema should be a function');
p = _compileAsync(schemaObj);
}
}
var p = Promise.resolve().then(function () {
schemaObj = self._addSchema(schema);
return schemaObj.validate || _compileAsync(schemaObj);
});

if (callback) {
p.then(
Expand All @@ -45,20 +36,16 @@ function compileAsync(schema, callback) {


function _compileAsync(schemaObj) {
var validate;
try { validate = self._compile(schemaObj); }
try { return self._compile(schemaObj); }
catch(e) {
return e.missingSchema
? loadMissingSchema(e)
: Promise.reject(e);
if (!e.missingSchema) throw e;
return loadMissingSchema(e);
}
return Promise.resolve(validate);


function loadMissingSchema(e) {
var ref = e.missingSchema;
if (self._refs[ref] || self._schemas[ref])
return Promise.reject(new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'));
if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');

var schemaPromise = self._loadingSchemas[ref];
if (!schemaPromise) {
Expand All @@ -67,19 +54,17 @@ function compileAsync(schema, callback) {
}

return schemaPromise.then(function (sch) {
if (!(self._refs[ref] || self._schemas[ref])) {
try {
self.addSchema(sch, ref);
} catch(e) {
return Promise.reject(e);
}
}
if (!added(ref)) self.addSchema(sch, ref);
return _compileAsync(schemaObj);
});

function removePromise() {
delete self._loadingSchemas[ref];
}

function added(ref) {
return self._refs[ref] || self._schemas[ref];
}
}
}
}

0 comments on commit 48cee59

Please sign in to comment.