虽然我有点搞清楚了Koa流机制是如何工作的(我认为),但我似乎无法理解co和co.wrap之间的所有区别。这是给出意外行为的代码:
"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);对此代码的输出如下:
Checking against String
{ [ValidationError] name: 'ValidationError', object: 11, schema: undefined }
### WRAP ###
11您可以看到,我对co.wrap的使用进行了包装,以便它能够在简单的协同使用之后使用。很明显,typeGen在第二次尝试中没有被调用,但是为什么会这样呢?这两种结果不应该是相同的吗?
发布于 2015-09-20 21:41:19
这只是非常常见的problem of calling "unbound" methods。
您仍然需要将包装函数作为validator实例上的方法调用。例如,您可以在call函数上使用validate:
var validate = co.wrap(validator.validate);
validate.call(validator, 11).then(console.log, console.error);或者,您需要.bind()该方法:
var validate = co.wrap(validator.validate.bind(validator));
validate(11).then(console.log, console.error);或者更好的是,只需将生成器函数包装到其定义的点,以便该方法总是立即返回一个承诺:
ValidatorWithSchema.prototype.validate = co.wrap(function* (obj) {
…
});
…
validator.validate(11).then(console.log, console.error);https://stackoverflow.com/questions/32684420
复制相似问题