[英]Is there a way to wait for the calculations before moving to next iteration in Javascript
在以下函數中,對應於else if
條件的productId
和reqQuantity
的計算完成之前。 運行后的命令。
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
....
您可以更改訂單並將promise存儲在變量中。 之后,您只需在變量上調用.then()
。
addBasketItem.quantityCheck = () => (req, res, next) => { var promise; //Some stuff going on here.. promise = models.BasketItem.findAll({ where: { id: pID.replace('/', '') } }); //After "else if (req.method === 'PUT')" (Or somewhere else..) promise.then(item => { productId = item[0].dataValues.ProductId; console.log("productIdInside:", productId); reqQuantity = result[0].value; 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) }); }); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.