节点javascript函数执行顺序[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我试图将req.session.cartprod.quantityprod.qtyCount的更新值传递到shoppingCartorder.save()

但问题是订单将保存数量和qtyCount的默认值,即使我正在做cartProducts[i].prod.quantity = productDbQty;cartProducts[i].prod.qtyCount = getQtyArr;

奇怪的是,如果我做第二个订单,那么第二个订单将反映第一个订单的数量。所以基本上如果默认数量是100并且用户传入的新数量是50,则第一个订单将保存,默认值为100。第二个订单,无论数量传递的是什么,都将保存50,这应该是订单1的数量。

在我的模型中

// function to get an array of the quantity
module.exports.getProductCount = (qty) => {
    var productCountArr = [];  
    for (var i=0; i <= qty; i++) {
        productCountArr.push(i);
    };
    return productCountArr;
};

更新我添加了一堆console.log(num)语句,所以我可以看到发生的执行顺序。它按预期从步骤1,2,3开始,然后跳转到9,10,11,这使得订单保存为默认数量。然后返回步骤4,更新订单值。因此,在数量更新发生之前,它会过早保存订单。不知道怎么解决它。

出于某种原因,它正在跳过Product.find()然后保存订单然后返回查找产品以更新它,但到那时订单已经保存。

输出,显示console.log()语句的执行顺序。

1
2
3
9
10
11
4
5
6
7
8

在我的控制器中

  // save an order to the database
module.exports.saveOrder = 
    (req, res, next) => {

    // if there is a current user logged in
    if (req.user) {
        // // create a new order
        // let order = new Order({
        //     // get the shopping cart from the session
        //     shoppingCart: req.session.cart, 
        //     // get the user id from passport
        //     userId: req.user.id,
        //     orderTotal: Number(req.session.cart.cartTotal),
        //     orderQuantity: Number(req.session.cart.cartQuantity)
        // });

        console.log('1');

        // get the shopping cart object from the session
        // var cart = req.session.cart;
        var cart = new Cart(req.session.cart);

        // get the products from the session cart
        var products = cart.products;

        console.log('2');

        // loop through the products in the cart
        for (var id in products) {

            // quantity the user selected for the product in their session cart
            prodSessionCartQty = Number(products[id].quantity);

            console.log('3');

            // get the product model quantity and subtract
            Product.findById(id, (err, prod) => {
                if (err)
                    console.log("Error Selecting : %s ", err);
                if (!prod)
                    return res.render('404');

                    // the number of products in the product database collection
                    var productDbQty = Number(prod.quantity);

                    console.log('4');

                    // if their are enough products in the database
                    if (productDbQty >= prodSessionCartQty) {
                        // subtract the product session cart quantity 
                        productDbQty = productDbQty - prodSessionCartQty;
                        prod.quantity = productDbQty;  // store the new quantity

                        // update array of quantity count in product collection
                        var qty = prod.quantity;
                        var getQtyArr = ProductDb.getProductCount(qty);
                        prod.qtyCount = getQtyArr;       

                        console.log('5');

                        // get the products in the shopping cart
                        var cartProducts = cart.products;

                        // array to hold the products of an order
                        var productsArray = [];

                        // loop through the products in the cart
                        for (var i in cartProducts) {

                            console.log('6');

                            // update quantities for prods in order collection
                            cartProducts[i].prod.quantity = productDbQty;
                            cartProducts[i].prod.qtyCount = getQtyArr;

                            // push the products into an array
                            productsArray.push(cartProducts[i]);
                        };
                        // store the updated prod quantities back in the cart object
                        cart.products = productsArray;
                        req.session.cart = cart;

                        console.log('7');

                        // save the new updated quantity to the database
                        prod.save((err, updatedProd) => {

                            console.log('8');

                            console.log(err, updatedProd);
                            if (err) {
                                res.status(500).send('save failed');
                                return;
                            }
                        });

                    }//if
            }); // Product   
        } //for

        console.log('9');

        // create a new order
        let order = new Order({
            // get the shopping cart from the session
            shoppingCart: req.session.cart,
            // get the user id from passport
            userId: req.user.id,
            orderTotal: Number(req.session.cart.cartTotal),
            orderQuantity: Number(req.session.cart.cartQuantity)
        });
        console.log('10');

        order.save((err, resultCallback) => {
            console.log('11');

            // if an error occurs during checkout
            if (err) {
                console.log("Error Selecting : %s ", err);
                req.flash('errorMessage', 'Error: checkout failed!')
                res.redirect('/orders/checkout');
            }
            // else no error while checking out
            else {
                // set cart back to null so a new order can be made
                req.session.cart = null;
                req.flash('successMessage', 'Your order has been placed')
                res.redirect('/products');                
            }
        });

    // else no logged in user
    } else {
        // redirect user and send login message
        req.flash('errorMessage', 'Please login first!');
        res.redirect('/login');
    }
};
javascript node.js express-session
1个回答
0
投票

这条线const getQtyArr = ProductDb.getProductCount(qty);可能是一个承诺。如果是这种情况,则在循环运行之后才返回值。这可以解释为什么以下订单会看到之前的价值。使用async / await并等待解决此问题可能会解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.