在运行函数之前异步/等待返回承诺

时间:2021-05-20 19:21:25

标签: javascript node.js asynchronous promise

我正在尝试在异步路由中映射一个函数,但 res.send 在该函数之前触发并返回一个承诺。我已经尝试重新安排我调用 async 和 await 的位置,但到目前为止还没有任何运气让它工作。

路线

router.post('/garageOrders', requireLogin, async (req, res) => {
    let {month} = req.body
    try {
        const LocationMonth = await Orders.distinct("location", {"date" : {$regex : ".*Apr.*"}});
        const LocationObj = LocationMonth.map((item) => calcTotals(item));
        console.log(LocationObj);
        res.send(LocationObj);
    } catch {
        res.status(400).send("No Garages Found");
    }
})

calcTotal 函数

const calcTotals = async (item) => {
    let newTotal = 0;
    let newQuantity = 0;
    await Orders.find({ $and: [{"date" : {$regex : ".*Apr.*"}}, {location: item}]})
        .then(resp => {
            resp.forEach((order) => {
                newTotal = order.total + newTotal;
                newQuantity = newQuantity + 1;
            })
            console.log(item.name);
            console.log(newTotal);
            console.log(newQuantity);
            console.log('///////////////////////////////////////');
        })
    return {
        name: item.name,
        total: newTotal,
        quantity: newQuantity
    }
}

console.log(数据计算正确,但未在承诺之前返回。)

[
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> }
]
Miranova
85
1
///////////////////////////////////////
75 East Main Street
125
1
///////////////////////////////////////
Bicentennial Lot
125
1
///////////////////////////////////////
#722 South High Garage
410
2
///////////////////////////////////////
107 Garage
240
2
///////////////////////////////////////
City of Columbus Parking Garage
480
4
///////////////////////////////////////
SHERATON HOTEL VALET - COLUMBUS
560
5
///////////////////////////////////////
LEVEQUE GARAGE
120
1
///////////////////////////////////////
Crazy Joes Parking Garage
190
1
///////////////////////////////////////

0 个答案:

没有答案