向回调函数添加参数

时间:2019-04-01 18:58:54

标签: javascript

想将参数传递给回调函数,不确定如何使用这种格式

player.GetPlayer((name,surname) -> {
    var thisPlayerId = player.id;
});

在这种情况下,可能会将用户名和密码添加到GetPlayer函数中

 module.exports = class Player{

constructor(){
    this.username = ""
    this.id = 0;

}

GetPlayer(Callback,name,surname)
{   
    console.log(name)
    console.log(surname)
    var player = this;
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records
        request.query('SELECT * FROM Table WHERE name = UserName ', function (err, result,fields) {

            if (err) console.log(err)

            // send records as a response
            //console.log(result.recordset[0].PlayerID);
            player.username = result.recordset[0].UserName;
            player.id = result.recordset[0].PlayerID;
            sql.close();
    Callback();
        });
    });
}

}

2 个答案:

答案 0 :(得分:0)

在Java中,您必须使用->而不是=>

编辑。

因此,如果您使用的是JavaScript,则只需定义在函数上接收到回调

function doHomework(subject, callback) {
  alert(`Starting my ${subject} homework.`);
  callback();
}

doHomework('math', function() {
  alert('Finished my homework');
});

答案 1 :(得分:0)

在您的GetPlayer函数中

GetPlayer(Callback,name,surname){
...
}

将所需的参数添加到“回调”中

// query to the database and get the records
 request.query('SELECT * FROM Table WHERE name = UserName ', function (err, result,fields) {

    // callback
    // now your are able to access username&password in your callback function
    Callback(username, password, ...);
    
});