【问题标题】:Meteor wrapAsync usingMeteor wrapAsync 使用
【发布时间】:2016-05-07 18:15:05
【问题描述】:

每个人。 Meteor 应用程序有点麻烦。 需要使用读/写数据库来执行一些算法。但这是一个问题:每个 R/W 操作都依赖于先前的数据库操作。 我尝试使用 wrapAsync 方法解决这个问题,但它对我不起作用。请帮我包装我的数据库调用,将其作为同步代码执行。

这是我的函数,它使用数据库调用:

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;
}

这是访问数据库的原始函数:

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}
    });
}

我试着修改它。我明白了:

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);
}

它返回给我功能代码而不是数据库文档值。 请告诉我我做错了什么。

【问题讨论】:

    标签: javascript asynchronous meteor


    【解决方案1】:

    我找到了解决办法。 我的错误是 - Meteor.wrapAsync 必须采用最后一个参数为回调的函数。

    解决方案代码:

     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);
    

    现在我可以打电话了

    use_coupon_sync(coupon._id);
    

    作为一个常规函数,将同步运行并返回结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      相关资源
      最近更新 更多