2017-09-11 36 views
0

我在node.js中有一個api,它通過它的名字找到類別的id,當結果出現時,它將這個id發送給另一個函數,並調用它的所有父類別id。如果沒有任何父類別,則在數組它應該被添加,如果有父類別,那麼它也應該被添加到數組中。我的問題是,響應發送一個空數組,只是因爲異步調用。如何使這個同步通過異步瀑布?請幫助我。謝謝提前如何使節點js api同步激發mongodb的多個查詢?

router.post('/api/getproductofcategory', function(req, res) { 
     var name = req.body.category; 
     var cidarray = []; 

     Category.getCategoryIdByname(name, function(err, categoryId) { 
     if (err) { 
      throw err; 
     } 

     if (categoryId.length) { 
      console.log(categoryId); 
      Category.getcategoryWithSameParentFun(categoryId[0]._id, function(
      err, 
      categoryWithSameParent 
     ) { 
      if (err) { 
       throw err; 
      } else { 
       console.log(categoryWithSameParent); 
       if (categoryWithSameParent.length == 0) { 
       cidarray.push(categoryId[0]._id); 
       } else { 
       cidarray.push(categoryWithSameParent._id); 
       } 

Product.getProductByCategoryid(cidarray[0], function(err, products){ 
       if(err){ 
        console.log('error', err); 
       } 
       else{ 
        console.log(products); 
          } 

      }) 
} 
      }); 
     } 
     }); 

     res.end('result', cidarray); 
    }); 
+0

基本上我沒有看到那裏的循環。所以在Category.getcategoryWithSameParentFun()的回調中移動'res.end(...)'似乎就足夠了。 –

+0

我已經更新了我的代碼above.here當cidarray有多個cid的,那麼我的產品功能將運行多次。爲此我必須使用async-waterfall併發送所有產品作爲響應。 –

+0

'Product.getProductByCategoryid'對'cidarray'做什麼? –

回答

0

我改變的變量名了一下,做了一些評論。我不知道你爲什麼要發送cidarray作爲API響應,但無論如何,這是你如何基本上控制你的流量async/each

const each = require('async/each'); 

router.post('/api/getproductofcategory', function(req, res) { 
    var name = req.body.category; 
    var cidarray = []; 

    Category.getCategoryIdByname(name, function(err, categoryIds) { 
    if (err) { 
     throw err; 
    } 

    each(
     categoryIds, 
     function(categoryId, callback) { 
     Category.getcategoryWithSameParentFun(categoryId._id, function(
      err, 
      categoryWithSameParent 
     ) { 
      if (err) { 
      throw err; 
      } else { 
      if (categoryWithSameParent.length == 0) { 
       cidarray.push(categoryId[0]._id); 
      } else { 
       cidarray.push(categoryWithSameParent._id); 
      } 
      callback(); 
      } 
     }); 
     }, 
     function(err) { 
     // Here your cid array is filled with desired values. 

     each(
      cidarray, 
      function(cid, callback) { 
      Product.getProductByCategoryid(cid, function(err, products) { 
       if (err) { 
       console.log('error', err); 
       } else { 
       // Don't know exactly what you're trying to do with products here. 
       // Whatever it is you should call callback() after you do your job with each cid. 
       console.log(products); 
       } 
      }); 
      }, 
      function(err) { 
      // Final step. You end your response here. 
      res.end('result', cidarray); 
      } 
     ); 
     } 
    ); 
    }); 
}); 
+0

不,我想發送產品作爲我的迴應 –

+0

@Amansharma然後你聲明產品變量和推產品在console.log(產品)。 –

+0

好的謝謝你。我檢查你的代碼 –