首页 > 解决方案 > 有没有办法在 Javascript 中移动到下一次迭代之前等待计算

问题描述

在下面的函数之前计算productIdreqQuantity完成对应的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()
  }
}

标签: javascriptnode.jsasynchronouscallbackasync-await

解决方案


您可以为此使用 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
    .... 

推荐阅读