首页 > 解决方案 > 异步 Qestiong Node.js

问题描述

我是 Node.js 的新手,我已经习惯了异步语言并且不熟悉同步处理方式。我正在开发一个基本的结帐功能,即结帐用户购物车中的项目并获得总数。sql 工作正常,但我很难得到总数。请在下面查看我的代码

exports.checkout = (req, res) =>{
    const schema = {
        user_id: joi.number().required(),
	}
	const results = joi.validate(req.body,schema)
	if (results.error){
		//or someother redirect
		res.status(400).send(results.error)
		return;
    }
	let data = {
        user_id: req.body.user_id
    };

    let order_id ;
    let total = 0 ;
        //first create order entry for the products and movies in the shopping cart
    query = "INSERT INTO Order_table (user_id,order_time) VALUES (?, NOW());"; 
    db.query(query,[data.user_id], async(err, resp) => {
        if(err){
            res.status(500).send(err);
            console.log(`Check out Order [SQL ERROR]: ${err}`)
        } 
        else{
            console.log('Created order');
            order_id=await resp.insertId;
            console.log(order_id)
            
            await console.log(await get_total(data.user_id,await order_id,res));
            //await res.send(Promise.all(total));
            //res.status(200).send(await total);
            }
        })
        
    
        
        
}

async function check_out_product(user_id,order_id,res){
    var total = 0;
    //Find all the products with details that is in the shopping cart belong to the given user_id.
    query = "Select product_id,quantity,unit_price,product_tax_code from Shoping_Cart_Product join product on Shoping_Cart_Product.product_id  = product.id where user_id =?"; 
    await db.query(query,[user_id], async (err, resp) => {
        if(err){
            res.status(500).send(err);
            console.log(`Check out Product [SQL ERROR]: ${err}`)
        } 
        else{
            console.log(`Check out product`)
            if(resp){
                // For each product insert them into the Order Detail table 
                await resp.forEach(async function(value){
                    //console.log(value['product_id']);
                    query = "INSERT INTO Order_Detail_Products (id, product_id,order_id,quantity) VALUES ((select id from (select * from Order_Detail_Products) AS temp where temp.order_id = ? and product_id=? ),?,?,?) ON DUPLICATE KEY UPDATE quantity = ?"
                    await db.query(query,[order_id,value['product_id'],value['product_id'],order_id,value['quantity'],value['quantity']], async (err, resp) => {
                        if(err){
                            res.status(500).send(err);
                            console.log(`Product order Insert [SQL ERROR]: ${err}`)
                        } 
                        else{
                            console.log(`Product Order is inserted`)
                            total = await total + (value['quantity'] * value['unit_price'])
                            await console.log('current total is',total)
                        }
                    })
                });
                //after the insertion is done, delete the original entry from the shopping cart product table.
                query = "Delete from Shoping_Cart_Product where user_id=?"
                await db.query(query,[user_id], (err, resp) => {
                    if(err){
                        res.status(500).send(err);
                        console.log(`Shopping Cart Product delete [SQL ERROR]: ${err}`)
                    } 
                    else{
                        console.log(`Shopping Cart Product is emptied`)
                    }
                })
                
                
            }
            //res.status(200).send(resp[0]);
           
        }
    })
    return Promise.resolve(total); 
}


async function check_out_movie(user_id,order_id,res){
    var total = 0;
    //Find all the movies with details that is in the shopping cart belong to the given user_id.
    query = "Select movie_id,method,price_rent,price_buy from Shoping_Cart_Movie join movie on Shoping_Cart_Movie.movie_id  = movie.id where user_id =?"; 
    await db.query(query,[user_id],async (err, resp) => {
        if(err){
            res.status(500).send(err);
            console.log(`Check out Movie [SQL ERROR]: ${err}`)
        } 
        else{
            await console.log(`Check out Movie`)
            if(resp){
                // For each product insert them into the Order Detail table 
                await resp.forEach(async function(value){
                    var isrent;
                    if (value['method']=="rent"){
                        isrent = 0;
                    }else{
                        isrent =1;
                    }
                    query = "INSERT INTO Order_Detail_Movie (id, movie_id,order_id,isrent,duration) VALUES ((select id from (select * from Order_Detail_Movie) AS temp where temp.order_id = ? and movie_id=? ),?,?,?,DATE_ADD(NOW(), INTERVAL 7 DAY)) ON DUPLICATE KEY UPDATE isrent = ?"
                    await db.query(query,[order_id,value['movie_id'],value['movie_id'],order_id,isrent,isrent], async (err, resp) => {
                        if(err){
                            res.status(500).send(err);
                            console.log(`Movie order Insert [SQL ERROR]: ${err}`)
                        } 
                        else{
                            console.log(`Movie Order is inserted`)
                            if(isrent == 1){
                                total = await total + value['price_rent']
                                await console.log('current total is',total)
                            }else{
                                total = await total + value['price_buy']
                                await console.log('current total is',total)
                            }
                        }
                       
                    })
                    
                });
                //after the insertion is done, delete the original entry from the shopping cart movie table.
                query = "Delete from Shoping_Cart_Movie where user_id=?"
                await db.query(query,[user_id], async (err, resp) => {
                    if(err){
                        res.status(500).send(err);
                        await console.log(`Shopping Cart Movie delete [SQL ERROR]: ${err}`)
                    } 
                    else{
                        await console.log(`Shopping Cart Movie is emptied`)
                    }
                })
                
            }   
        }
    })
    return Promise.resolve(total);  

}
async function get_total(user_id,order_id,res){
    total = check_out_movie(user_id,order_id,res);
    total += check_out_product(user_id,order_id,res,total);
    return await total;
}

我得到的输出如下:

Created order
77
[object Promise][object Promise]
Check out Movie
Check out product
Shopping Cart Movie is emptied
Product Order is inserted
current total is 3.99
Shopping Cart Product is emptied

我想知道为什么在处理函数之前会记录承诺,尽管我为此函数调用设置了等待。以及如何从这个 console.log() 中得到数字输出

标签: javascriptnode.jsasynchronous

解决方案


推荐阅读