Although I kind of figured out how the Koa flow mechanims work (I think), I can't seem to grasp all of the differences between co and co.wrap. This is the code that is giving the unexpected behavior:
"use strict";
var co = require("co");
function ValidationError(message, obj, schema) {
Error.call(this, "Validation failed with message \"" + message + "\".");
this.name = "ValidationError";
this.object = obj;
this.schema = schema;
}
ValidationError.prototype = Object.create(Error.prototype);
function ValidatorWithSchema(properties, schema) {
this.properties = properties;
this.schema = schema;
}
ValidatorWithSchema.prototype.validate = function* (obj) {
var validatedObj = obj;
for (let schemaKey in this.schema) {
validatedObj = yield this.properties[schemaKey](validatedObj, this.schema[schemaKey]);
}
return validatedObj;
};
var typeGen = function* (obj, type) {
console.log("Checking against "+ type.name);
var primitives = new Map([
[String, "string"],
[Number, "number"],
[Boolean, "boolean"]
]);
if (!((obj instanceof type) || (primitives.has(type) && (typeof obj === primitives.get(type))))) {
var error = new ValidationError("Given object is not of type " + type.name, obj);
throw error;
}
return obj;
};
var validator = new ValidatorWithSchema({type: typeGen}, {type: String});
var runWrap = r => {
console.log(r);
console.log("### WRAP ###");
var validate = co.wrap(validator.validate);
validate(11).then(console.log, console.error);
};
co(function* () {
yield validator.validate(11);
}).then(runWrap, runWrap);
The output to this code follows:
Checking against String
{ [ValidationError] name: 'ValidationError', object: 11, schema: undefined }
### WRAP ###
11
You can see that I wrapped the use of co.wrap in order for it to be subsequent to the simple co use. Now it is evident that typeGen
is not getting called in the second attempt, but why is this the case? Shouldn't the two outcomes be identical?