2016-07-04 122 views
0

我使用node.js與mongodb和q.js承諾。Node.js鏈接承諾使用q.js

以下是我的MongoDB架構:

{ 
    UserId: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'User' 
    }, 
    FirstName: String, 
    LastName: String, 
    Gender: String, 
    userDocument: [userDocumentSchema], 
    userEducation: [userEducationDetailsSchema] 
}; 
var userEducationDetailsSchema = new Schema({ 
    DegreeName: String, 
    University: String, 
}); 
var userDocumentSchema = new mongoose.Schema({ 
    DocumentName: String, 
    DocumentPath: String 
}); 


I have following function by chaining promises: 

var updateUserDetails = function (req, res) { 
    var finalResult = []; 
    /* This is the function to update user using promise.*/ 
    updateUserBasicDetails(req).then(function (req) { 
    _.each(req.body.userEducation, function (sd) { 
     return getEducationDetail(req.body._id, sd) /* this fun finds if education details are present or not by iterating usertEducation Array */ 
     .then(function (result) { 
      if (result) { 
      /* if education details exist then this will update the details */ 
      return updateEducationDetails(sd, req.body._id).then(
       function (result) { 
       return result; 
       }) 
      } else { 
      /*else add the education details*/ 
      return addEducationDetails(sd, req.body._id).then(
       function (result) { 
       return result; 
       }) 
      } 
     }).then(function (result) { 
      finalResult.push(result); 
     }) 
    }) 
    return JSON.stringify(finalResult); 
    }).then(function (finalResult) { 
    res.json({ 
     "token": finalResult /*but here m getting empty result */ 
    }) 
    }).catch(console.log).done(); 
} 

我的查詢是:

  1. 這是實現承諾的chainging的正確方法?
  2. 在最後的鏈中,我得到空結果,但是當我打印o/p到控制檯我得到正確的結果。
  3. 我已經完成了getEducationDetail函數的迭代,這是正確的方式還是有其他選擇。如果是這樣,我怎麼能達到相同的。
+1

要返回'finalResult'同步,但值只是異步填充。 – thefourtheye

回答

0

你的代碼可以更清潔,請調整一些地方像這樣

var updateUserDetails = function (req, res) { 
    var finalResult = []; 
    /* This is the function to update user using promise.*/ 
    return updateUserBasicDetails(req) 
    .then(function (req) { 
     _.each(req.body.userEducation, function (sd) { 
     return getEducationDetail(req.body._id, sd) 
      .then(function (result) { 
      if (result) { 
       return updateEducationDetails(sd, req.body._id) 
      } 
      else { 
       return addEducationDetails(sd, req.body._id) 
      } 
      }) 
      .then(function (result) { 
      return result; 
      }) 
      .then(function (result) { 
      finalResult.push(result); 
      }) 
     }) 

     return JSON.stringify(finalResult); 
    }) 
    .then(function (finalResult) { 
     res.json({ 
     "token": finalResult /*but here m getting empty result */ 
     }) 
    }) 
    .catch(function (e) { console.log(e); }) 
    .done(); 
} 

和上面的代碼還可以是更清潔,如果更換_.each,並使用q.all代替。

  • 注意:您使用JavaScript ES5,使你的代碼很長,可以縮短它使用JavaScript ES6和使用箭頭函數,而不是function(x, y) {}