簡體   English   中英

ExpressJS - Javascript 似乎不是自上而下執行的

[英]ExpressJS - Javascript doesn't seem to execute from top-down

我有這個似乎沒有用完的腳本。 我在變量重新分配的部分注意到了它。 顯示代碼片段和 output

//Create New Open Market under the game
            let latestRowId = 1;
            var sqlQuery2 = "SELECT ID FROM markets ORDER BY LAST_EDITED DESC LIMIT 1";
            db.query(sqlQuery2, [], function(err, result4) {
                if (err){
                    console.log("Error during /openBetoBetoMarket. Proc_4" + err);
                    res.status(500).json({ msg: "Server Error /openBetoBetoMarket. gameID:" + gameID });
                } else {
                    console.log("result4", result4[0].ID)
                    latestRowId = result4[0].ID
                }
            });
            console.log("latest_row_id", latestRowId);
            
            newRowID = latestRowId + 1
            newMarketId = result[0].MARKET_ID + 1
            newGameId = gameID
            newDescription = gameTitle
            console.log("New row id", newRowID, "new market id", newMarketId)

            sqlQuery = "INSERT INTO markets (ID, MARKET_ID, GAME_ID, DESCRIPTION, LAST_EDITED, WRITER) VALUES (?, ?, ?, ?, NOW(), CURRENT_USER);"
            db.query(sqlQuery, [newRowID, newMarketId, newGameId, newDescription], (err, result4) => {
                if (err){
                    console.log("Error during /openBetoBetoMarket. Proc_5 " + err);
                    res.status(500).json({ msg: "Server Error /openBetoBetoMarket. gameID:" + gameID });
                } else if (result4.affectedRows > 0){
                    console.log("Created new open market for /openBetoBetoMarket. MarketID: " + newMarketId);
                    res.status(200).json({msg: "Created New Open Market", marketID: newMarketId, isOpen: 1})     
                } else {
                    console.log("Error during /openBetoBetoMarket. Proc_5. Inserted but no affected Rows");
                    res.status(500).json({ msg: "Server Error /openBetoBetoMarket. gameID:" + gameID });
                }
            })

Output如下圖:

latest_row_id 1
新行 id 2 新市場 id 3
結果 4 2
/openBetoBetoMarket 期間出錯。 Proc_5 錯誤:ER_DUP_ENTRY:鍵“markets.PRIMARY”的重復條目“2”

如您所見,它似乎跳過了第一個 db.query 並直接進入下一個變量賦值,然后執行第一個 db.query。 知道我在這里缺少什么嗎? 第一次在這里發帖。 謝謝

您定義(或根本不定義)變量的方式會給您帶來麻煩。

首先,放棄var關鍵字。 絕對沒有理由使用它。 var在全局 scope 中定義變量,並允許重新分配它們。 除了永遠不會顯着改變的最小腳本外,您真的永遠不應該使用全局變量。 在極少數情況下,您實際上想要重新分配一個變量,但如果您這樣做,請使用let關鍵字,因為那樣您至少有塊級范圍。

其次,在中途你有四個變量定義錯誤,根本沒有任何關鍵字。 JavaScript 語法定義一個變量是不正確的,如下所示:

// wrong! this is correct in Python but not JS

varName = <value>;

您需要使用letconstvar之一。 建議使用const

重寫你的代碼以使用正確的變量定義,看看你是否可以用一種不重新分配變量來獲得獎勵積分的方式來編寫你的代碼。 然后您應該會發現您的代碼不會產生意外的結果。

祝你好運

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM