javascript - 有没有办法在 Javascript 中移动到下一次迭代之前等待计算
问题描述
在下面的函数之前计算productId
和reqQuantity
完成对应的else if
条件。运行之后的命令。
addBasketItem.quantityCheck = () => (req, res, next) => {
if (req.method === 'POST' || req.method === 'PUT') {
// console.log(extractParam(req))
var result = utils.parseJsonCustom(req.rawBody)
var productId = 0
var reqQuantity = 0
if( req.method === 'POST') {
var productIds = []
var basketIds = []
var quantities = []
for (var i = 0; i < result.length; i++) {
if (result[i].key === 'ProductId') {
productIds.push(result[i].value)
} else if (result[i].key === 'BasketId') {
basketIds.push(result[i].value)
} else if (result[i].key === 'quantity') {
quantities.push(result[i].value)
}
}
productId = productIds[0]
console.log("productIdInstantiated:", productId)
reqQuantity = quantities[0]
} else if (req.method === 'PUT') {
var pID = req.url
models.BasketItem.findAll({ where: { id: pID.replace('/', '') } }).then((item) => {
productId = item[0].dataValues.ProductId <---- Here
console.log("productIdInside:", productId)
reqQuantity = result[0].value <---- Here
})
}
console.log("productIdQueried:", productId)
models.Product.findAll({ where: { id: productId } }).then((product) => {
const availableQuantity = product[0].dataValues.quantity
if (availableQuantity < reqQuantity) {
res.status(401).send('{\'error\' : \'Quantity Unavailable\'}')
} else {
next()
}
}).catch(error => {
next(error)
})
} else {
next()
}
}
解决方案
您可以为此使用 async/await:
addBasketItem.quantityCheck = async (req, res, next) => {
if (req.method === 'POST' || req.method === 'PUT') {
// console.log(extractParam(req))
var result = await utils.parseJsonCustom(req.rawBody)
var productId = 0
var reqQuantity = 0
....
推荐阅读
- terraform - terraform 是否支持 AWS BACKUP 还原功能?
- c# - 当前线程必须设置为单线程单元 (STA) 模式错误 DataGridView
- python - skimage.morphology 中的深度学习语法错误
- python - 将双端队列值转换为索引列表的最佳方法?
- reactjs - 如何使用 onClick 获取要为组件加载的路由路径?
- linux - 与 SIGTERM 一起传递其他信息
- html - 如何使用 Flexbox 进行网格布局
- java - 我如何一次有效地更新一个类的数千个实例?
- c# - 自动售货机中的 3 层架构,同时保持 OCP
- java - 有没有办法使用 itext 库清理扫描的 pdf 的矩形区域?