NodeJS 如何在javascript中等待变量更新以进行新计算

z9gpfhce  于 2022-12-03  发布在  Node.js
关注(0)|答案(1)|浏览(215)

嘿,我正试图建立 Jmeter 板计算我的药品供应商总未偿使用nextjs。

  • 下面 * 是我的createPurchaseAPI。

`

import PurchaseOrder from '../../models/PurchaseOrder'
import Supplier from '../../models/Supplier'
import connectDB from '../../middleware/mongoose';
import Medicine from '../../models/Medicine';

const handler = async (req, res) => {
    if (req.method === 'POST') {

        const medicines = [];
        let totalOrderAmount = 0;
        let totalPaybleGst = 0;

        req.body.medicines.forEach(async medicine => {

            let medicineOne = await Medicine.findById(medicine.medicine)
            let newQuantity = parseInt(medicineOne.quantity) + parseInt(medicine.quantity)
            const filter = { _id: medicine.medicine };
            const update = { quantity: newQuantity };

            await Medicine.findByIdAndUpdate(filter, update);

            let newmedi = {
                name: medicine.name,
                company: medicine.company,
                medicine: medicineOne,
                quantity: newQuantity,
                pack_detail: medicine.pack_detail,
                category: medicine.category,
                batch: medicine.batch,
                mrp: medicine.mrp,
                rate: medicine.rate,
                gst: medicine.gst,
                totalAmount: medicine.totalAmount,
                expiryDate: medicine.expiryDate
            }

            totalOrderAmount += medicine.totalAmount;
            totalPaybleGst += medicine.gst * medicine.rate * medicine.quantity * 0.01;
            medicines.push(newmedi);
        })

        const paidAmount = req.body.paidAmount

        const supplierBeforeUpdate = await Supplier.findById(req.body.supplier);
        const newOustanding = supplierBeforeUpdate.totalOutstanding + totalPaybleGst + totalOrderAmount - paidAmount;

        const filter = { _id: req.body.supplier };
        const update = { totalOutstanding: newOustanding };

        await Supplier.findOneAndUpdate(filter, update);
        const supplierAffterUpdate = await Supplier.findById(req.body.supplier);

        const purchaseOrder = await PurchaseOrder.create({
            supplier: supplierAffterUpdate,
            createdBy: req.body.createdBy,
            medicines: medicines,
            paybleGst: totalPaybleGst,
            totalAmount: totalOrderAmount,
            grandTotal: totalPaybleGst + totalOrderAmount,
            paidAmount: paidAmount
        })
        res.status(200).json({ success: true, purchaseOrder: purchaseOrder })
    }
    else {
        res.status(400).json({ error: "This method is not allowed" })
    }
}

export default connectDB(handler);

这是我的**purchaseOrder架构**

const mongoose = require('mongoose');
const { Schema, model, models } = mongoose;

const medicinePurchaseSchema = new Schema({
    name: { type: String, required: true },
    company: { type: String, required: true },
    medicine: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Medicine'
    },
    quantity: { type: Number, required: true },
    pack_detail: { type: String, required: true },
    batch: { type: String, required: true },
    mrp: { type: Number, required: true },
    rate: { type: Number, required: true },
    gst: { type: Number, required: true },
    totalAmount: { type: Number, required: true },
    expiryDate: { type: Date, required: true }
});

const purchaseOrderSchema = new Schema({
    supplier: { type: Object, required: true},
    createdBy: { type: String, required: true },
    medicines: [medicinePurchaseSchema],
    paybleGst: { type: Number, required: true },
    totalAmount: { type: Number, required: true },
    paidAmount: { type: Number, required: true },
    grandTotal: { type: Number, required: true }
}, { timestamps: true })

const PurchaseOrder = models.PurchaseOrder || model('PurchaseOrder', purchaseOrderSchema);

export default PurchaseOrder;

const mongoose = require('mongoose');
const { Schema, model, models } = mongoose;

const medicineSchema = new Schema({
    name: { type: String, required: true },
    company: {type: String, required: true},
    pack_detail: {type: Number, required: true},
    quantity: { type: Number, required: true },
    category: { type: String, required: true },
    status: { type: String, required: true }
}, { timestamps: true });

const Medicine = models.Medicine || model('Medicine', medicineSchema);

export default Medicine;

'这是我的医学模式
但问题是我得到的totalOrderAmounttotalPayableGst在newOutstanding计算中是0,我认为我的 *newOutstanding计算行在更新我的这些变量 * 之前正在执行。
我怎么能解决这个问题,我尝试了2天,但我没有得到任何解决方案。
任何人都有解决办法。

q3qa4bjr

q3qa4bjr1#

forEach方法调用将同步执行,不等待任何承诺。回调确实有await,但这些回调只影响它们出现的async函数,而不影响forEach方法。
不要使用forEach,而使用map,这样就可以得到promises数组(因为async回调函数返回promise)。为了确保这些promise解析为有用的内容,让这些回调函数返回newmedi。使用Promise.all,您可以知道所有promise何时解析,并将所有medicine值存储在medicines数组中。并且仅在完成该操作后才继续执行函数的其余部分:

// Not forEach, but map, and await all returned promises
const medicines = await Promise.all(req.body.medicines.map(async medicine => {
    /* ...rest of your callback code... */
    return newmedi; // Don't push, but return it
}));

相关问题