0

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 の使用の後に co.wrap の使用をラップしたことがわかります。2 回目の試行で が呼び出されないことは明らかですtypeGenが、なぜそうなるのでしょうか? 2 つの結果が同一であってはなりませんか?

4

1 に答える 1