0

使用 node.js,socket.io 正在调用 onRegister() 来检查用户的 mongoDB。但是数据库回调函数是预定义的,如何在回调参数中添加'this'(ioHandle)?

function onRegister(data) {
    var name,pass,room;
    name = data.name;
    pass = data.pass;
    ioHandle = this;

    Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db, ioHandle) { // wrong
        if(err) throw err;
        var collection = db.collection('users');

        // does user exist
        collection.findOne({name : name}, function(err, doc, ioHandle) { // wrong
            if(err) throw err;
            if(doc) {
                log("User already exists");
                ioHandle.emit(NGC_REGISTER_RESULT, {NGC_REJECT:"User already Exists"}); // ioHandle undefined
            } else {
                // create new user
                log("User not found");
                ioHandle.emit(NGC_REGISTER_RESULT, NGC_ACCEPT); // ioHandle undefined
            }
            db.close();
        });
    });
}

错误: ioHandle 没有被传递

TypeError: Cannot call method 'emit' of undefined
4

1 回答 1

0

您不需要添加ioHandlefindOne回调函数,ioHandle将通过正常的 JavaScript 闭包机制在该函数的范围内:

function onRegister(data) {
    // ioHandle will be visible to everything inside this function,
    // that includes the callback and nested callback below.
    var ioHandle = this;
    //...

    Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db) {
        //...
        collection.findOne({name : name}, function(err, doc) {
            // Use ioHandle as normal in here
            //...

您可能想花一点时间在MDN 关闭页面上

于 2013-09-01T05:28:25.273 回答