diff --git a/lib/compile/async.js b/lib/compile/async.js index 16f46c4..aebffbc 100644 --- a/lib/compile/async.js +++ b/lib/compile/async.js @@ -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( @@ -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) { @@ -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]; + } } } }