亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在javascript中返回嵌套函數的值?

如何在javascript中返回嵌套函數的值?

素胚勾勒不出你 2023-03-03 19:33:01
我在項目中有一個功能function findParentID(parentName) {  Category.findOne({ categoryName: parentName }, function (err, foundParent) {    var parentID = foundParent.categoryID;    return parentID;  });}module.exports.findParentID = findParentID;當我嘗試調用此函數時,我進入了undefinedThis console.log() is how I am trying to call itvar parentName = req.body.parent_name;var parentID = findParentID(parentName);console.log(parentID);根據我的理解,該函數沒有返回任何值。如何從函數返回值?
查看完整描述

1 回答

?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

在您的代碼中,您試圖直接調用具有 db(async) 操作的函數。


要么使用 promises/async await。一旦相應地返回值,就執行連續的操作


function findParentID(parentName) {

return new Promise((resolve,reject)=>{

  Category.findOne({ categoryName: parentName }, function (err, foundParent) {

    var parentID = foundParent.categoryID;

    resolve(parentID);

  });

});


}

module.exports.findParentID = findParentID;



var parentName = req.body.parent_name;

   findParentID(parentName).then((parentID)=>{

   console.log(parentID);

  

  });

  


更新(根據建議)


  var parentName = req.body.parent_name;

    Category.findOne({ categoryName: parentName }).then(foundParent => {

   

     var parentID = foundParent.categoryID;

      console.log(parentID);

    })

  


查看完整回答
反對 回復 2023-03-03
  • 1 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號