简体   繁体   中英

Meteor wrapAsync using

everyone. Have a little trouble with Meteor Application. Need to execute some algorithm with using reading/writing to database. But it is a problem: each R/W operation is dependent on previous database operation. I try to resolve this proplem with using wrapAsync method, but it does not work for me. Please help me to wrap my database calls, to execute it as synchronous code.

Here is my function, that use database calls:

function calc_item_discount(item){
    var discount = 0;
    while(item.count){
        coupon = get_coupon(item.item_id);
        if(!coupon){return discount;}

        discount += (item.order_item.price /100) * coupon.discount;
        use_coupon(coupon._id);
        item.count--;
    }
    return discount;
}

Here is original functions to acces database:

function get_coupon(item_id){
    return coupons.findOne({menu_item_id:item_id});
}

function use_coupon(coupon_id){
    coupons.update({_id:coupon_id},{
        $inc:{count:-1}
    });
}

I trye to modify it. I get:

function get_coupon(item_id){
    var get_coupon_async = Meteor.wrapAsync(coupons.findOne({menu_item_id:item_id},function(err, res){
        if(!err) {
            console.log('return coupon');
            return res;}
        else {
            console.log('retreiving coupon error');
            return false;
        }
    }));
    return get_coupon_async(item_id);
}

It return me function code instead database document value. Please tell me what i do wrong.

I find a solution. My mistake is - Meteor.wrapAsync must take function with last parametr is callback.

Solution code:

 function use_coupon(coupon_id, callback){
        coupons.update({_id:coupon_id},
            {$inc:{count:-1}},
            function(err,res){
                callback(err,res);
            });
    }

var use_coupon_sync = Meteor.wrapAsync(use_coupon);

now i can call

use_coupon_sync(coupon._id);

as a regular function which will run synchronously and return the result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM