有没有一种方法可以等待计算,然后再进行Javascript的下一次迭代

时间:2019-05-13 15:37:12

标签: javascript node.js asynchronous callback async-await

在下面的函数中,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()
  }
}

2 个答案:

答案 0 :(得分:1)

您可以为此使用async / wait:

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
    .... 

答案 1 :(得分: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)
    });
  });
}