首页 > 解决方案 > JS for 循环的异常行为?

问题描述

我正在编写一个简单的 node.js 脚本,它遍历一组数字。我可以在 for 循环中看到,它正在被正确读取。

但是,当它进入数据库查询函数时,它只显示所有的 +1 值,而不是实际的索引循环计数。

结果

Processing:  1
Processing:  2
Processing:  3
Processing:  4
Processing:  5
Processing:  6
Processing:  7
Processing:  8
Processing:  9
Processing:  10
Create New Bottle for  11
Create New Bottle for  11
Create New Bottle for  11
Create New Bottle for  11
Create New Bottle for  11
Create New Bottle for  11
Create New Bottle for  11
Create New Bottle for  11
Create New Bottle for  11
Create New Bottle for  11

预期的

Processing:  1
Processing:  2
Processing:  3
Processing:  4
Processing:  5
Processing:  6
Processing:  7
Processing:  8
Processing:  9
Processing:  10
Create New Bottle for  1
Create New Bottle for  2
Create New Bottle for  3
Create New Bottle for  4
Create New Bottle for  5
Create New Bottle for  6
Create New Bottle for  7
Create New Bottle for  8
Create New Bottle for  9
Create New Bottle for  10

代码
ProcessBottleGeneration()

async function ProcessBottleGeneration() {

    try {


        var start = 1
        var end = 10
        
        for (count = start; count <= end; count++) {
            console.log("Processing: ", count)

            GetByUniqueCode(count).then(result => {

                if (result == undefined) {
                    console.log("Create New Bottle for ", count)

                    // AddBottleData(bottle).then(res => {
                    //     console.log(res)
                    // }).catch(err => {
                    //     console.log(err)  
                    // })
                }
                else {
                    console.log("Bottle exist already for ", count)
                }

                // process.exit()
            })
                .catch(error => {
                    console.log("error: ", error)
                    return error
                })

        }

    } catch (error) {
        console.log("ProcessBottleGeneration.Error:")
        console.log(error)
        return error
    }
}

function GetByUniqueCode(unique_code) {
    var where = [
        unique_code
    ]

    let sql = `SELECT  *
        FROM
            plants_bottles
        WHERE
            unique_code =  ?;`

    return new Promise((resolve, reject) => {
        db.query(sql, [where], function (err, result) {
            if (err) {
                return reject(err)
            } else {
                return resolve(result[0])
            }
        });
    })
}

function AddBottleData(d) {
    console.log("AddBottleData:", d)

    let sql = `INSERT INTO plants_bottles SET ?;`

    return new Promise((resolve, reject) => {
        query = db.query(sql, [d], function (err, result) {

            console.log("AddBottleData.result:", result)
            if (err) {
                return reject(err)
            } else {
                return resolve(result)
            }

        });
    })

}

我会错过什么?

标签: javascriptnode.js

解决方案


推荐阅读