简体   繁体   English

JavaScript function 返回 0 值

[英]JavaScript function returning 0 value

I am writing a route for a node app and calling a function to calculate the totals of all orders at a given location.我正在为节点应用程序编写路线并调用 function 来计算给定位置的所有订单的总数。 I am able to console.log the correct values inside of the map function (line 12 + 13), but when I return the variable I am getting 0 still.我能够控制台记录 map function (第 12 + 13 行)中的正确值,但是当我返回变量时,我仍然得到 0。 I tried moving the return into the map function but then it returns null for each value.我尝试将返回移动到 map function 但随后它为每个值返回 null。

Edit: I declared newTotal and newQuantity right away in the calcTotals function and am adding to them in the map function.编辑:我立即在 calcTotals function 中声明了 newTotal 和 newQuantity,并在 map function 中添加了它们。

router.post('/garageOrders', requireLogin, async (req, res) => {
    let {month} = req.body
    try {
        const LocationMonth = await Orders.distinct("location", {"date" : {$regex : ".*Apr.*"}});
        //.find({$contains:{"date": {$regex: `.*${month}.*`}}});
        const calcTotals = (item) => {
            let newTotal = 0;
            let newQuantity = 0;
            Orders.find({ $and: [{"date" : {$regex : ".*Apr.*"}}, {location: item}]})
                .then(resp => {
                    resp.map((order) => {
                        console.log(order.total + newTotal)
                        console.log(order.location.name)
                        console.log('///////////////////////////////////////')
                        newTotal = order.total + newTotal;
                        newQuantity = newQuantity + 1;
                    })
                })
            console.log(newTotal)
            return {
                name: item.name,
                total: newTotal,
                quantity: newQuantity
            }
        }
        const LocationObj = LocationMonth.map((item) =>  calcTotals(item));
        console.log(LocationObj);
        res.send(LocationObj);
    } catch {
        res.status(400).send("No Garages Found");
    }
})

console.log控制台日志

85
Miranova
///////////////////////////////////////
125
75 East Main Street
///////////////////////////////////////
135
SHERATON HOTEL VALET - COLUMBUS
///////////////////////////////////////
270
SHERATON HOTEL VALET - COLUMBUS
///////////////////////////////////////
405
SHERATON HOTEL VALET - COLUMBUS
///////////////////////////////////////
525
SHERATON HOTEL VALET - COLUMBUS
///////////////////////////////////////
560
SHERATON HOTEL VALET - COLUMBUS
///////////////////////////////////////
125
Bicentennial Lot
///////////////////////////////////////
205
#722 South High Garage
///////////////////////////////////////
410
#722 South High Garage
///////////////////////////////////////
190
Crazy Joes Parking Garage
///////////////////////////////////////
120
107 Garage
///////////////////////////////////////
240
107 Garage
///////////////////////////////////////
120
LEVEQUE GARAGE
///////////////////////////////////////
120
City of Columbus Parking Garage
///////////////////////////////////////
240
City of Columbus Parking Garage
///////////////////////////////////////
360
City of Columbus Parking Garage
///////////////////////////////////////
480
City of Columbus Parking Garage
///////////////////////////////////////

res.send重新发送

[
    {
        "name": "Miranova",
        "total": 0,
        "quantity": 0
    },
    {
        "name": "75 East Main Street",
        "total": 0,
        "quantity": 0
    },
    {
        "name": "SHERATON HOTEL VALET - COLUMBUS",
        "total": 0,
        "quantity": 0
    },
    {
        "name": "Bicentennial Lot",
        "total": 0,
        "quantity": 0
    },
    {
        "name": "#722 South High Garage",
        "total": 0,
        "quantity": 0
    },
    {
        "name": "107 Garage",
        "total": 0,
        "quantity": 0
    },
    {
        "name": "City of Columbus Parking Garage",
        "total": 0,
        "quantity": 0
    },
    {
        "name": "Crazy Joes Parking Garage",
        "total": 0,
        "quantity": 0
    },
    {
        "name": "LEVEQUE GARAGE",
        "total": 0,
        "quantity": 0
    }
]

Your map function is part of the asynchronous code and the return is outside of that asynchronous code.您的 map function 是异步代码的一部分,并且返回在该异步代码之外。 The function is returning before the map probably gets the data. function 在 map 可能获取数据之前返回。 Try something like this尝试这样的事情

router.post('/garageOrders', requireLogin, async (req, res) => {
  let {month} = req.body
  try {
      const LocationMonth = await Orders.distinct("location", {"date" : {$regex : ".*Apr.*"}});
      //.find({$contains:{"date": {$regex: `.*${month}.*`}}});
      const calcTotals = async (item) => {
          let newTotal = 0;
          let newQuantity = 0;
          let ordersRes = await Orders.find({ $and: [{"date" : {$regex : ".*Apr.*"}}, {location: item}]})
          ordersRes.forEach((order) => {
                      console.log(order.total + newTotal)
                      console.log(order.location.name)
                      console.log('///////////////////////////////////////')
                      newTotal = order.total + newTotal;
                      newQuantity = newQuantity + 1;
                  })
          console.log(newTotal)
          return {
              name: item.name,
              total: newTotal,
              quantity: newQuantity
          }
      }
      const LocationObj = await LocationMonth.map(async (item) =>  await calcTotals(item));
      console.log(LocationObj);
      res.send(LocationObj);
  } catch {
      res.status(400).send("No Garages Found");
  }
})

Unfortunately I can't test it to make sure it works, but using async await will help with making sure the data returns before mapping over it and returning.不幸的是,我无法对其进行测试以确保其正常工作,但使用 async await 将有助于确保数据在映射并返回之前返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM