Problem with frappe.db.get_value

Hey everyone,
Can’t figure what is wrong here?
I am trying to calculate the dish price as per quantity of the produce used.
two problem here:

  1. When hitting “ud_price” button, without the alert("updated"); line, the price is 0.
  2. My computer runs the VM where the frappe is installed. On a colleague machine, the result is always 0.
frappe.ui.form.on('Dish', {
	refresh(frm) {
    cur_frm.cscript.ud_price = function(doc) {
            var material;
        var price = 0;
        var materialType;
        var total_price = 0;
        var priceDataSource;
        var recipeTable = frm.doc.recipes;
        var qty;
    	$.each(recipeTable, function(index, row){
		material = row.cat_num;
		materialType = "Produce";
    		frappe.db.get_value(materialType,material,'var_price')
   		.then(r => {
    		    qty = row.var_quant / 100;
                price = r.message.var_price;
                total_price = total_price + price * qty;
   		});
   	});`
       alert("updated");
        frm.set_value('var_price',total_price);
    };
}
});

Any ideas?

Well found a way to bypass the issue (can’t understand how or why):

frappe.ui.form.on('Dish', {
	refresh(frm) {
    cur_frm.cscript.ud_price = function(doc) {
        var material;
        var price;
        var materialType;
        var total_price=0;
        var priceDataSource;
        var recipeTable = frm.doc.recipes;
        var qty;
        frm.set_value('var_price',total_price);
    	$.each(recipeTable, function(index, row){
	material = row.cat_num;
    			materialType = "Produce";
    		}
    		frappe.db.get_value(materialType,material,'var_price')
    		.then(r => {
    		    qty = row.var_quant / 100;
                price = r.message.var_price;
    		    total_price = frm.doc.var_price + (price * qty);
    		    frm.set_value('var_price',total_price);
    		});
    	});
    };
	}

Basically all I did is reinserting to calculated price into the loop.
works both on my computer and on my colleague’s.

1 Like

In my naive understanding, the get_value happens asynchronously, therefore in your first code block it may, or may not be finished when calling frm.set_value. → second approch is the correct one here.

1 Like