javascript - 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)
}
});
})
}
我会错过什么?
解决方案
推荐阅读
- ios - 在 Cloud Functions 中发送 VoIP 推送通知
- c# - 如何创建不同类型的 JSON 数据模型
- javascript - 如何延迟 CSS 动画,直到滚动到 React 中的元素?
- c++ - stof 引发的异常 - C++
- windows - Windows alpha 合成 XOR 模式
- python - Python:如何从数组中的数组中提取项目?
- python - 将整个 ascii 字符串转换为 int
- react-native - undefined 不是对象(评估“data.length”)
- typescript - Typescript — 确保对象 prop 键与 prop 值相同
- c++ - 如何使用 decltype 获取没有引用的指针?