使用异步-等待socket.io nodejs

时间:2020-06-30 12:43:57

标签: node.js promise socket.io async-await angular9

我正在使用nodejs socket.io和angular 9开发一个Web应用程序。在我的后端代码中,我已经在socket.connect.service中编写了套接字。 接下来是我正在使用的套接字

socket.on('request-to-sit-on-the-table', async function (data, callback) { //Previously Register
    let table = persistence.getTable(tableToken);
    if (typeof table === 'undefined') {
        let errMsg = 'This table does not exists or already closed.'
        callback(prepareResponse({}, errMsg, new Error(errMsg)));
        return;
    }
    //TODO: Get the displayName from the token.
    let guest = await guestUserService.getGuestUserByPlayerToken(JSON.parse(data.userToken));***//Here is the issue***
    // let displayName = 'DisplayName-' + guest;
    let displayName = 'DisplayName-' + Math.random();

    //TODO: Check whether the seat is available

    // If the new screen name is not an empty string
    let isPlayerInCurrentTable = persistence.isPlayerInCurrentTable(tableToken, userToken);
    if (displayName && !isPlayerInCurrentTable) {
        var nameExists = false;
        let currentPlayersTokenArr = persistence.getTableObjectPlayersToken(table)
        for (var token in currentPlayersTokenArr) {
            let gamePlayer = persistence.getPlayerPlayer(currentPlayersTokenArr[token])
            if (typeof gamePlayer !== "undefined" && gamePlayer.public.name === displayName) {
                nameExists = true;
                break;
            }
        }
        if (!nameExists) {
            //Emit event to inform the admin for requesting to sit on the table.
            let ownerToken = persistence.getTableObjectOwnerToken(table);
            let ownerSocket = persistence.getPlayerSocket(ownerToken);
            ownerSocket.emit('requested-to-sit', {
                seat: data.seat,
                secondaryUserToken: userToken,
                displayName,
                numberOfChips: envConfig.defaultNumberOfChips
            });
            callback(prepareResponse({userToken}, 'Player connected successfully.'));
        } else {
            callback(prepareResponse({}, 'This name is already taken'));
        }
    } else {
        callback(prepareResponse({}, 'This user has already joined to a game. Try clear caching'));
    }

});

在我的代码中,我从guest.user.service中的另一个代码获取数据。但我对“来宾”的值不确定 以下是我在guest.user.service

中使用的方法
exports.findById = (id) => {
    return new Promise(function(resolve, reject) {
        guestUserModel.findById(id, (err, data) =>{
            if(err){
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
};
exports.getGuestUserByPlayerToken = (playerToken) => {
    var player = playerService.findOne({ token: playerToken })
        .then(function (data) {
            return self.findById(data.guestUser._id.toString());
        })
        .then(function (guestUser) {
            return guestUser.displayName;
        })
        .catch(function (err) {
            throw new Error(err);
        })
};

虽然我获得了displayName作为返回值,但它没有传递给套接字中的“ guest”。在使用promises时是否存在语法问题来获取数据?请帮助

1 个答案:

答案 0 :(得分:0)


exports.getGuestUserByPlayerToken = async playerToken => {
   try {
     let player = await playerService.findOne({token:playerToken});
     return playerService.findById(player.guestUser._id)
   } catch(error) {
     console.log(error);
     return null;
   }
};

这只是等待的诺言的处理错误而未返回一个。您需要在呼叫方进行处理。