节点javascript函数的执行顺序

时间:2019-03-02 22:44:51

标签: javascript node.js express-session

我正在尝试将req.session.cartprod.quantity的更新值的prod.qtyCount传递到shoppingCart中的order.save()字段

但是问题是即使我正在执行cartProducts[i].prod.quantity = productDbQty;cartProducts[i].prod.qtyCount = getQtyArr;

,订单也将使用默认的数量和qtyCount保存。

奇怪的是,如果我进行第二次订购,该第二次订购将反映第一次订购的数量。因此,基本上,如果默认数量是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');
    }
};

1 个答案:

答案 0 :(得分:0)

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