首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Co和co.wrap在Node.js中的行为不同

Co和co.wrap在Node.js中的行为不同
EN

Stack Overflow用户
提问于 2015-09-20 21:19:11
回答 1查看 2.4K关注 0票数 0

虽然我有点搞清楚了Koa流机制是如何工作的(我认为),但我似乎无法理解co和co.wrap之间的所有区别。这是给出意外行为的代码:

代码语言:javascript
复制
"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);

对此代码的输出如下:

代码语言:javascript
复制
Checking against String
{ [ValidationError] name: 'ValidationError', object: 11, schema: undefined }
### WRAP ###
11

您可以看到,我对co.wrap的使用进行了包装,以便它能够在简单的协同使用之后使用。很明显,typeGen在第二次尝试中没有被调用,但是为什么会这样呢?这两种结果不应该是相同的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-20 21:41:19

这只是非常常见的problem of calling "unbound" methods

您仍然需要将包装函数作为validator实例上的方法调用。例如,您可以在call函数上使用validate

代码语言:javascript
复制
var validate = co.wrap(validator.validate);
validate.call(validator, 11).then(console.log, console.error);

或者,您需要.bind()该方法:

代码语言:javascript
复制
var validate = co.wrap(validator.validate.bind(validator));
validate(11).then(console.log, console.error);

或者更好的是,只需将生成器函数包装到其定义的点,以便该方法总是立即返回一个承诺:

代码语言:javascript
复制
ValidatorWithSchema.prototype.validate = co.wrap(function* (obj) {
    …
});

…
validator.validate(11).then(console.log, console.error);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32684420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档