节点js中async中的多个回调

时间:2017-01-20 06:45:43

标签: javascript node.js asynchronous callback

我是节点j的新手,我在异步方法的瀑布中调用了多个回调。

var offer = new Offer(req.body);
        offer.featured_tag=false;
        var err = '';
        reserror='';
        async.waterfall([
            function (done) {
                if(req.body.create_role === 'Merchant' || req.body.create_role=== 'SubMerchant'){
                    //if offer created by merchant is less than than the subscription of merchant then active this offer when adding otherwise deactive
                    offer.active_immediately=false;
                    Offer.find({ merchant_id:req.body.merchant_id }).populate('merchant_id').exec(function(err, offerscount) {
                        //  count no of offers createdBy merchant
                        console.log(offerscount);
                        var noofrecords=offerscount.length;
                        if(noofrecords>0){
            if(typeof offerscount[0].merchant_id.more_details.fields!=='undefined'){
                            if(offerscount[0].merchant_id.more_details.fields.subscription){
                                if(noofrecords<offerscount[0].merchant_id.more_details.fields.subscription.number_offer){
                                    offer.active_immediately=true;
                                }
                                if(offerscount[0].merchant_id.more_details.fields.subscription.feature_tag === true){
                                    offer.featured_tag=true;
                                }
                            }
                            if(req.body.loyalty_offer==true){
                              Offer.find({ merchant_id:req.body.merchant_id,loyalty_offer:true }).populate('merchant_id').exec(function(err, loyaltyoff) {
                                console.log('count:'+loyaltyoff.length);
                                if(loyaltyoff.length>0){
                                    if(loyaltyoff.length===offerscount[0].merchant_id.more_details.fields.subscription.loyalty_offers){
                                      console.log('hello');
                                /*     reserror = {
                                          "status":0,
                                          "data":"",
                                          "message":"Exceeds the loyalty offers limit."
                                      };*/
                                      reserror = 'Exceeds the loyalty offers limit.';

                                        done(err, reserror);


                                    }
                                }

                             });
                          }
                        }


                              done(err, 'debug1');

                        }
                 }else if(req.body.create_role === 'Admin'){
                    done(null,'debug1')
                 }
            }, function(err, reserror) {
                console.log('load');
                var startdate = new Date(req.body.startdate);
                offer.startdate = startdate.toISOString();
                var enddate = new Date(req.body.enddate);
                offer.enddate = enddate.toISOString();
                offer.createdOn=Date.now();
                offer.createdBy=req.body.creater_id;
                offer.isDeleted= false;
                offer.offer_image=req.body.image;
                console.log('bug'+err);
                if(err!='debug1'){
                  var reserror1 = {
                       "status":0,
                       "data":"",
                       "message":'Exceeds the loyalty offers limit.'
                   };
                   res.json(reserror1);

                }else{
                  offer.save(function(err,data) {
                      if (err) {
                          response = {
                              "status":0,
                              "error":err
                          };
                      }else{
                          Category.findById(req.body.main_cat, function (err, catdataset) {
                              var offerset = {
                                  offer_id: data._id,
                                  posted_by: data.createdBy,
                                  datetime: data.createdOn
                              };
                              catdataset.offers.push(offerset);
                              catdataset.save();
                          });
                          response = {
                              "status":1,
                              "data":data,
                              "message":"Offer has been created."
                          };
                      }
                      console.log(response);
                      res.json(response);
                  });
                }
            }
        ]);

在上面的代码中如果完成(错误,reserror); 是在完成后调用(错误,'debug1'); .it不等待reserror所以我想先检查错误,如果reserror不为null或为空,则只调用 done(错误,'debug1'); 否则调用 done(错误,reserror); 。请帮助我找到解决方案。谢谢所有人提前。

2 个答案:

答案 0 :(得分:0)

您应该使用不同的名称来表示错误。假设以下服务错误名称为err1且顶级服务错误名称为错误

Offer.find({ merchant_id:req.body.merchant_id,loyalty_offer:true })
              .populate('merchant_id').exec(function(err1, loyaltyoff) {

  if(loyaltyoff.length>0){

   if(loyaltyoff.length===
            offerscount[0].merchant_id.more_details.fields.subscription.loyalty_offers){
        console.log('hello');
        reserror = 'Exceeds the loyalty offers limit.';

        if (reserror !== null && reserror !== undefined) {
            done(err, 'debug1');
        } else {
            done(err1, reserror);
        }

   }
 });

答案 1 :(得分:0)

尝试以下代码。

var offer = new Offer(req.body);
        offer.featured_tag=false;
        var err = '';
        reserror='';
 async.waterfall([
            function (done) {
                if(req.body.create_role === 'Merchant' || req.body.create_role=== 'SubMerchant'){
                    //if offer created by merchant is less than than the subscription of merchant then active this offer when adding otherwise deactive
                    offer.active_immediately=false;
                    Offer.find({ merchant_id:req.body.merchant_id }).populate('merchant_id').exec(function(err, offerscount) {
                        //  count no of offers createdBy merchant
                        console.log(offerscount);
                        var noofrecords=offerscount.length;
                        if(noofrecords>0){
            if(typeof offerscount[0].merchant_id.more_details.fields!=='undefined'){
                            if(offerscount[0].merchant_id.more_details.fields.subscription){
                                if(noofrecords<offerscount[0].merchant_id.more_details.fields.subscription.number_offer){
                                    offer.active_immediately=true;
                                }
                                if(offerscount[0].merchant_id.more_details.fields.subscription.feature_tag === true){
                                    offer.featured_tag=true;
                                }
                            }
                            if(req.body.loyalty_offer==true){
                              Offer.find({ merchant_id:req.body.merchant_id,loyalty_offer:true }).populate('merchant_id').exec(function(err, loyaltyoff) {
                                console.log('count:'+loyaltyoff.length);
                                if(loyaltyoff.length>0){
                                    if(loyaltyoff.length===offerscount[0].merchant_id.more_details.fields.subscription.loyalty_offers){
                                      console.log('inside loyalty');
                                     reserror = {
                                          "status":0,
                                          "data":"",
                                          "message":"Exceeds the loyalty offers limit."
                                      };
                                    //  reserror = 'Exceeds the loyalty offers limit.';

                                      done(err, reserror);
//return res.json(reserror);
//next();

                                    }else{
                                      done(err, 'debug1');
                                    }
                                }else{
                                  done(err, 'debug1');
                                }

                             });
                          }else{
                            done(err, 'debug1');
                          }
                        }else{
                          done(err, 'debug1');
                        }

                 }else if(req.body.create_role === 'Admin'){
                    done(null,'debug1')
                 }
            }, function(err, reserror) {
                console.log('load');
                var startdate = new Date(req.body.startdate);
                offer.startdate = startdate.toISOString();
                var enddate = new Date(req.body.enddate);
                offer.enddate = enddate.toISOString();
                offer.createdOn=Date.now();
                offer.createdBy=req.body.creater_id;
                offer.isDeleted= false;
                offer.offer_image=req.body.image;
                console.log('bug'+err);
                if(err!='debug1'){
                  var reserror1 = {
                       "status":0,
                       "data":"",
                       "message":'Exceeds the loyalty offers limit.'
                   };
                   return res.json(reserror1);

                }else{
                  offer.save(function(err,data) {
                      if (err) {
                          response = {
                              "status":0,
                              "error":err
                          };
                      }else{
                          Category.findById(req.body.main_cat, function (err, catdataset) {
                              var offerset = {
                                  offer_id: data._id,
                                  posted_by: data.createdBy,
                                  datetime: data.createdOn
                              };
                              catdataset.offers.push(offerset);
                              catdataset.save();
                          });
                          response = {
                              "status":1,
                              "data":data,
                              "message":"Offer has been created."
                          };
                      }
                      console.log(response);
                      res.json(response);
                  });
                }
            }
        ]);