简体   繁体   中英

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. 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. I tried moving the return into the map function but then it returns null for each value.

Edit: I declared newTotal and newQuantity right away in the calcTotals function and am adding to them in the 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. The function is returning before the map probably gets the data. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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