【问题标题】:TypeError: promise.then(...).then(...).then(...).then(...).catch is not a function in Node Js [duplicate]TypeError:promise.then(...).then(...).then(...).then(...).catch 不是 Node Js 中的函数 [重复]
【发布时间】:2016-02-14 03:48:18
【问题描述】:

我收到此错误,我不知道如何解决它。 在节点 js 服务器中,我在 promise 上使用了一些 .then() 函数,最后我放置了一个 .catch() 函数,由于某种原因无法识别。 我在教程的很多地方都看到这是处理错误的方式。 我没有使用任何外部库。

错误:

 TypeError: promise.then(...).then(...).then(...).then(...).catch is not a function

这是我的代码:

exports.joinAlbum = function(req, res){


var promise = Album.findOne().where({'shortId': req.body.shortId}).exec(); // Returns a promise


promise.then(function(albumDoc){
    console.log('Then #1');

    .....

    }
    return albumDoc.save();  // Returns a promise
})



.then(function(albumDoc){
    console.log('Then #2');

    .....

    return User.findById(req.body.userId).exec(); // Returns a promise
})


.then(function(userDoc){
    console.log('Then #3');

     ........

    return userDoc.save();  // Returns a promise
})

//  Return a response
.then(function(savedUserDoc){
    console.log('Then #4');
    return res.status(200).json({success: true}); 
})

    //Error handler
.catch(function(err){
    console.log('Catch #1');
    console.log(err);
    res.status(200).json({success: false});
});
}

如果 .catch() 不是处理承诺错误的正确方法,你有什么建议?我试图避免使用外部库并更喜欢使用本机 javascript

编辑:解决方案

我添加了一个名为 blue-bird 的 npm 模块来帮助我解决这个问题。

【问题讨论】:

  • .catch() 用于try 块。如果在then 块中返回错误,则抛出一个新错误
  • 如果当前的answer 没有帮助,请说明Album.findOne().where() 返回什么样的Promise,如果不是ES6,在哪个库中。也许还包括您正在使用的 node.js 版本。

标签: javascript node.js promise


【解决方案1】:

看起来您正在使用 Mongoose,它返回自己的 Promise,而不是包含 catch 函数的 ES6 Promise。猫鼬 Promise 没有 catch 功能。幸运的是,您可以覆盖 Mongoose 使用的默认 Promise:

http://eddywashere.com/blog/switching-out-callbacks-with-promises-in-mongoose/

【讨论】:

  • 我不知道这些是不同的承诺!谢谢
猜你喜欢
  • 2020-04-05
  • 2016-01-21
  • 1970-01-01
  • 2015-09-10
  • 2020-10-22
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多