Node.js 函数调用部分代码两次

问题描述 投票:0回答:1

我正在学习 Node,但无法完全理解这里发生的事情。如果房间名称尚不存在,则该函数假设在 MongoDB 中创建一个聊天室文档。

const mongoose = require('mongoose');
const Chat = require("../Models/Chat");


async function CreateRoom(req, res) {
    const { room, username, _id } = req.body;
    console.log(`CHAT: createRoom ${room}`);

    const chat = await Chat.findOne({ "room": room }).exec();
    console.log(`____x`)    
    if (chat) {
        console.log(`____0`)
        res.sendStatus(409); // Conflict        
    }
console.log(`____1`)
    const result = await Chat.create({
        room: room,
        message: [
            {
                text: "Room created",
                from: _id,
            }
        ]
    });
    console.log("____2")    
    if (!result) {
        console.log(`CHAT: createRoom ${room} failed`);
        res.sendStatus(400);
    }
    console.log("____3")
    console.log(`CHAT room created: ${room}`);
    return res.sendStatus(201);
}

module.exports = { CreateRoom };

输出如下所示:

CHAT: createRoom lobby
____x
____1
____x
____1
____2
____3
CHAT room created: lobby
____2
____3
CHAT room created: lobby

我对“____x”以及其他重复项如何出现两次感到完全困惑。谁能告诉我这怎么可能?谢谢。

node.js mongoose async-await logic
1个回答
0
投票

原来有第二个电话正在发生。日志记录是隐藏的,直到我添加了更多日志记录。

************************************
REQUEST: OPTIONS /chat/create
************************************
CORS allowed  http://localhost:3000


************************************
REQUEST: OPTIONS /chat/create
************************************
CORS allowed  http://localhost:3000


************************************
REQUEST: POST /chat/create
************************************
CORS allowed  http://localhost:3000
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im1pa2UiLCJyb2xlcyI6IlVzZXIiLCJpYXQiOjE2OTgwMTIzMDcsImV4cCI6MTY5ODAxMzIwN30.i_lB5PFuKSqziXUbE8bu7oKFvKeFcJp70XcQufyRNoA
decoded: mike
CHAT: createRoom {lobby, mike,653579bf19d6b0f0082ad608


************************************
REQUEST: POST /chat/create
************************************
CORS allowed  http://localhost:3000
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im1pa2UiLCJyb2xlcyI6IlVzZXIiLCJpYXQiOjE2OTgwMTIzMDcsImV4cCI6MTY5ODAxMzIwN30.i_lB5PFuKSqziXUbE8bu7oKFvKeFcJp70XcQufyRNoA
decoded: mike
CHAT: createRoom {lobby, mike,653579bf19d6b0f0082ad608
____x
____0
____x
____0

“CHAT:createRoom”日志条目出现在第一篇文章中,然后发生第二篇文章,其余的日志记录看起来像是来自第二篇文章。

我在非线性思考方面仍然遇到一些困难。

© www.soinside.com 2019 - 2024. All rights reserved.