我正在尝试将自己的express.js
api用于nodejs。问题是它有效,但它出错了,我无法访问请愿的结果。这是我的代码:
routes.js:
app.post('/petition/:id', function(req, res) {
console.log("ID: ", req.params.id);
if (!req.params.id) {
return res.send({"status": "error", "message": "Chooser id needed"});
}
else {
indicoUtils.indicoPositivosNegativos(req.params.id).then(function(result) {
return res.send({"result": result});
})
}
})
calculator.js:
var indicoPositivosNegativos = function (chooserId) {
var TweetModel = mongoose.model('Tweet'.concat(chooserId), Tweet.tweetSchema);
TweetModel.find({},{ _id: 1, tweet: 1}).then(tweets =>
Promise.all(
tweets.map(({ _id, tweet }) =>
indico.sentiment(tweet).then(result =>
TweetModel.findOneAndUpdate({ _id }, { indicoPositivoNegativo: result }, { new: true })
.then( updated => { console.log(updated); return updated })
)
)
)
)
};
我正在使用Postman对此进行测试,并显示错误:
TypeError:无法读取属性.then of undefined
答案 0 :(得分:1)
这基本上意味着您尝试调用.then函数的其中一个对象是未定义的。
具体而言,对象indicoUtils.indicoPositivosNegativos(req.params.id)应该是一个承诺,但是你的函数indicoPositivosNegativos不会返回一个承诺。实际上你的函数没有返回任何东西,因此在未定义的值上调用.then。
解决方案很简单,你必须在calculator.js上添加一个return语句,以便返回这样的承诺:
var indicoPositivosNegativos = function (chooserId) {
var TweetModel = mongoose.model('Tweet'.concat(chooserId), Tweet.tweetSchema);
return TweetModel.find({},{ _id: 1, tweet: 1}).then(tweets =>
Promise.all(
tweets.map(({ _id, tweet }) =>
indico.sentiment(tweet).then(result =>
TweetModel.findOneAndUpdate({ _id }, { indicoPositivoNegativo: result }, { new: true })
.then( updated => { console.log(updated); return updated })
)
)
)
)
};
答案 1 :(得分:0)
TweetModel.find
创建的承诺不会从路由处理程序返回到调用函数。
var indicoPositivosNegativos = function(chooserId) {
var TweetModel = mongoose.model('Tweet'.concat(chooserId), Tweet.tweetSchema);
// THE PROMISE NEEDS TO BE RETURNED FOR CALLING FUNCTIONS
// TO HAVE ACCESS TO IT.
return TweetModel.find({}, {
_id: 1,
tweet: 1
}).then(tweets =>
Promise.all(
tweets.map(({
_id,
tweet
}) =>
indico.sentiment(tweet).then(result =>
TweetModel.findOneAndUpdate({
_id
}, {
indicoPositivoNegativo: result
}, {
new: true
})
.then(updated => {
console.log(updated);
return updated
})
)
)
)
)
};