簡體   English   中英

節點Promise-TypeError無法讀取未定義的屬性.then

[英]Node Promise - TypeError cannot read property .then of undefined

下面的兩段代碼引發類型錯誤:

TypeError:無法讀取未定義的屬性“ then”。

我覺得我缺少基本的東西。 值得注意的是,第二條代碼中的“結果”的日志是在引發錯誤之后完成的。 這使我相信,我可能在做涉及庇護的事情時出錯了。 但是,即使閱讀了建議的問題,我也仍然無法解決。

任何幫助將不勝感激!

router.route('/user/:id')

    .put(auth.authRest, function(req, res) {
      userManager.updateUser(req.params.id, req.body)
        .then(function(response) { // line where error is thrown
          res.send({data:response});
        });
    });

並從userManager中:

this.updateUser = function(id, data) {
    User.findOne({ _id: id }).exec(function(err, user){
      if(err) {
        console.log(err);
      } else {
        for(let prop in data) {
          user[prop] = data[prop];
        }

        var result = user.save().catch(function(err){
          console.log(err);
        });

        console.log(result); // this log is done below the error, it does contain a promise
        return result;
      } 
    }).catch(function(err){
      console.log(err);
    });

  };

如果要使用Promises,則需要從this.updateUser返回Promise, return result屬於您傳遞給exec的回調,而不屬於您分配給this.updateUser的函數。

this.updateUser = function(id, data) {
  return User.findOne({
    _id: id
  }).exec().then(function(user) {
    for (let prop in data) {
      user[prop] = data[prop];
    }

    var result = user.save().catch(function(err) {
      console.log(err);
    });

    console.log(result); // this log is done below the error, it does contain a promise
    return result;
  }).catch(function(err) {
    console.log(err);
  });

};

根據您要如何執行錯誤處理,可以將其縮減為:

this.updateUser = function(id, data) {
  return User.findOne({
    _id: id
  }).exec().then(function(user) {
    for (let prop in data) {
      user[prop] = data[prop];
    }

    return user.save();
  }).catch(function(err) {
    console.log(err);
  });
};

'updateUser'方法應返回一個Promise,以便第一個方法中的.then調用起作用。

嘗試以下類似操作(使用的節點包“ q”)

this.updateUser = function(id, data) {
    var deferred = Q.defer()
    User.findOne({ _id: id }).exec(function(err, user){
      if(err) {
        console.log(err);
        deferred.reject(err)
      } else {
        for(let prop in data) {
          user[prop] = data[prop];
        }

        var result = user.save().catch(function(err){
          console.log(err);
        });

        console.log(result); // this log is done below the error, it does contain a promise
        deferred.resolve(resolve)
        //return result;
      } 
    }).catch(function(err){
        deferred.reject(err)
      console.log(err);
    });

    return deferred.promise

  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM