【发布时间】:2023-03-31 00:02:02
【问题描述】:
我是 Node/Mongoose 的新手,我正在尝试在脚本中正确处理错误以将玩家添加到联赛中。在下面的代码中,.catch() 语句正确捕获了显式抛出的和非 Promise 相关的错误,但拒绝的 Promise 则没有。
例如,尝试传递无效的用户 ID 会抛出 User not found。
但如果我通过断开数据库连接来测试 Promise 拒绝,我会得到以下信息:
(node:6252) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
我是否以某种方式错误地使用了 Promise.all() 和 .catch()?
为了清楚起见,我试图找出错误没有得到处理的原因,而不是抛出错误的原因。
我的脚本:
const
mongoose = require('mongoose'),
User = require('./models/users'),
League = require('./models/leagues'),
dbUrl = process.env.DBURL || 'mongodb://localhost/predictor';
mongoose.connect(dbUrl, { useNewUrlParser: true });
const addUserToLeague = (userId, leagueId) => {
let foundUser = User.findById(userId);
let foundLeague = League.findById(leagueId);
return Promise.all([foundUser, foundLeague])
.then(arr => {
if(!arr[0]){
throw 'User not found';
}else if(!arr[1]){
throw 'League not found';
}
return arr;
})
.then(arr => {
arr[0].leagueMemberships.push(arr[1]);
arr[1].users.push(arr[0]);
return arr;
})
.then(updatedArr => {
updatedArr[0].save();
updatedArr[1].save();
return updatedArr;
})
.then(updatedArr => { console.log(`User ${updatedArr[0]._id} added to league ${updatedArr[1]._id}`) })
.catch(err => { console.log('Error:', err) });
};
addUserToLeague(process.argv[2], process.argv[3]); // Needs 2 args: User ID and League ID
【问题讨论】:
-
鉴于错误消息是
MongoNetworkError: failed to connect to server,听起来mongoose.connect(…)返回了一个被拒绝的承诺。 -
mongoose.connect()不是示例代码中承诺链的一部分。没有适用于它的 catch 块,因此当连接失败时,您会收到此错误。 -
^^
Promise.all的实际使用是可以的,尽管人们希望findById不会解决如果项目不是,则具有虚假值的承诺找到了,所以整个第一个then处理程序似乎没有必要。第二个then处理程序中的操作最好直接在findById承诺上处理。另外:save是否返回承诺?如果是这样,你就没有处理它的拒绝。 -
这里有一个很好的解释:github.com/petkaantonov/bluebird/issues/…
标签: javascript node.js promise