Async Qestiong Node.js - PullRequest
       1

Async Qestiong Node.js

0 голосов
/ 30 декабря 2018

Я новичок в 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 ()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...