mongoose 当放置在await之后时,Nodejs数组push为空

u0njafvf  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(170)

我尝试循环遍历一个数组,从数据库中获取每种股票的数量和价格,进行一些计算,然后将它们推送到一个数组中
但从数据库中获取数量和价格后,推送到数组中
数组仍将为空
如果我去掉这条线

const db_stock = await Stocks.findById(stock.stockId);

一切正常
但是如果我把await加回去数组就会变成空的

import mongoose from "mongoose";
import { response } from "express";
import  StockDispatches  from "../models/StockDispatch.js"
import  Stocks  from "../models/Stocks.js"
import { createError } from "../error.js";
import validator from 'express-validator'
const { validationResult } = validator
import { generateRamdom } from "../utils/Utils.js"

export const createStockDispatched = async (req, res, next) => {
    
  
    const error = validationResult(req).formatWith(({ msg }) => msg);
    const trx_id =  generateRamdom(30);
    let quantity = 0;
    let total = 0;
    let dispatchedTotal = 0;
    const hasError = !error.isEmpty();

    if (hasError) {
      res.status(422).json({ error: error.array() });
    } else {
        

        const options={ordered: true}; 
        let user_stocks =[];
        req.body.stocks.map(async (stock, index) => {
            let total = stock.price * stock.quantity

            const db_stock = await Stocks.findById(stock.stockId);
            if(!db_stock) return res.status(404).json({msg: "Stock Not Found."})
            
            if( stock.quantity > db_stock.quantity)
            return res.status(208).json({msg: `Quantity of ${stock.name} is greater than what we have in database`})

            quantity = db_stock.quantity - stock.quantity;
            total = quantity * db_stock.price;

            const updated_stock = await Stocks.findByIdAndUpdate(stock.id, {quantity, total},{$new: true})

            
            dispatchedTotal = stock.quantity * db_stock.price;
            user_stocks.push("samson")
            user_stocks.push({...stock, staffId: req.user.id, total: dispatchedTotal, trx_id, stockId: stock.id, price: db_stock.price})

        });
        
        

        try{
            const stockDispatched = await StockDispatches.insertMany(user_stocks, options);
            if(!stockDispatched) return res.status(500).json({msg: "Error. Please try again."})
            
            return res.status(200).json({msg: "Stock uploaded successfully.."})
        }catch(error){
            next(error)
        }
      
      
    }
}
w8ntj3qf

w8ntj3qf1#

解决此问题的最简单方法是更改

req.body.stocks.map()

至:

for (let [index, stock] of req.body.stocks.entries()) { ... }

因为for循环是promise-aware,它将在循环体中暂停循环以等待您的await,而.map()不会在回调中暂停循环以等待await

相关问题