gpt4 book ai didi

javascript - NodeJS Await 优先级 - 一个 Await 以错误的顺序在另一个 Await 之前运行(Express、SQLite3 db.all 和 db.run)

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:43 28 4
gpt4 key购买 nike

尝试在 .exports 中运行一个异步函数,获取 Promise,然后在下一个异步函数中使用结果,但由于某种原因,无论等待如何,第二个函数都会在第一个函数之前执行。

销售.js =

const sqlite3 = require('sqlite3').verbose()

const db = new sqlite3.Database('./database/stock.db', (err) => {
if (err) return console.error(err.message)
//console.log('Connected to the "stock.db" SQlite database.')
})

module.exports = {

total: function(cartlist) {
return new Promise((resolve) => {
var total = 0
for (x in cartlist){
console.log(cartlist[x].price)
total = total + cartlist[x].price
}
//console.log(total)
resolve(total)
})},

stockloss: function(cartlist) {
return new Promise((resolve) => {
var barcodes = []
const len = (cartlist).length
for(x in cartlist){
var inp = JSON.stringify(cartlist[x].name)
const sql = "SELECT barcode_id FROM products WHERE name ="+inp+";"
db.all(sql, (err, data) => {
if (err) console.error(err.message)
barcodes = barcodes.concat(data)
console.log(barcodes)
})}
resolve(barcodes)
})},

update: function(bars) {
return new Promise((resolve) => {
for(x in bars){
var bar = JSON.stringify(bars[x])
console.log(bar)
const sql = "UPDATE levels WHERE product_id ="+bar+" SET stock_level = stock_level - 1;"
db.run(sql, function(err) {
if (err) console.error(err.message)
console.log("Record updated. ")
})}
resolve()
})}
}
}

index.js(部分)=

'use strict'

const express = require('express')

const handlebars = require('express-handlebars').create({defaultLayout: 'main'})
const bodyParser = require('body-parser')
const app = express()
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: true }))
app.engine('handlebars', handlebars.engine)
app.set('view engine', 'handlebars')

const port = 8080

const sqlite3 = require('sqlite3').verbose()

const db = new sqlite3.Database('./database/stock.db', (err) => {
if (err) return console.error(err.message)
console.log('Connected to the "stock.db" SQlite database.')
})

const sales = require('./sale.js')

。。.

app.get('/checkout', async(req, res) => {
total = await sales.total(cartlist)
var bars = await sales.stockloss(cartlist)
var prom = await sales.update(bars)
cartlist = []
res.render('checkout', {total})
total = 0
})

。。.

不确定我是否在 promise 方面做错了什么,或者我对异步函数的理解不够。 db.run 也可能存在问题,因为我不断看到有关如何更新数据的不同来源。

最佳答案

我会这样做:

async function fetchFromDb(sql) {
return new Promise(resolve, reject) {
db.all(sql, (err, data) => {
if (err) {
console.error(err.message)
reject(err)
}
resolve(data)
})}
}

async function updateRecord(sql) {
return new Promise(resolve, reject) {
db.run(sql, function(err) {
if (err) {
console.error(err.message)
reject(err)
}
console.log("Record updated. ")
resolve()
}
}
}


module.exports = {

total: function(cartlist) {
return new Promise((resolve) => {
var total = 0
for (x in cartlist) {
console.log(cartlist[x].price)
total = total + cartlist[x].price
}
//console.log(total)
resolve(total)
})
},

stockloss: async function(cartlist) {
return new Promise((resolve) => {
var barcodes = []
const len = (cartlist).length
for (x in cartlist) {
var inp = JSON.stringify(cartlist[x].name)
const sql = "SELECT barcode_id FROM products WHERE name =" + inp + ";"
barcodes = barcodes.concat(await fetchFromDb(sql))
resolve(barcodes)
}
})
},

update: async function(bars) {
return new Promise((resolve) => {
for (x in bars) {
var bar = JSON.stringify(bars[x])
console.log(bar)
const sql = "UPDATE levels WHERE product_id =" + bar + " SET stock_level = stock_level - 1;"
try {
await updateRecord(sql)
} catch (err) {
reject(err)
}
resolve('successfully updated record')
}
})
}
}

顺便说一句,这尚未经过测试,但它应该有效,或者至少可以帮助您获得正确的想法。 fetchFromDb 存在于文件或对象中的某个位置。主要问题是将回调转变为 promise ,以便您可以等待结果并在解析运行之前连接结果......这就是问题所在。回调不会同步返回函数外部的结果。这就是您遇到的问题。

关于javascript - NodeJS Await 优先级 - 一个 Await 以错误的顺序在另一个 Await 之前运行(Express、SQLite3 db.all 和 db.run),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53662259/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com