【发布时间】:2020-01-09 05:24:49
【问题描述】:
我是 Node JS 的新手,在使用 Promise 时我很难正确处理错误。 这是我目前拥有的:
我有一个调用 db.js 的模块,它带有一个用于设置和启动 db 连接的 init 函数:
function initDb(){
return new Promise((resolve, reject) => {
if(database){
console.warn("Trying to init DB again !")
}else{
client.connect(config.db.url, {useNewUrlParser: true, useUnifiedTopology: true})
.then((client) => {
console.log("DB initialized - connected to database: " + config.db.name)
database = client.db(config.db.name)
})
.catch((err) => {
reject(err)
})
}
resolve(database)
})}
这个函数会返回一个promise,它会被index.js调用:
initDb()
.then(() => {
app.listen(8081, function () {
console.log('App is running on port 8081')
})
})
.catch((error) => {
console.log(error)
})
如您所见,我有两个问题。一个在 db 模块中,另一个在 index.js 中
在两个地方捕获错误看起来很奇怪......在这种情况下处理错误的好模式是什么?
【问题讨论】:
-
你为什么要设置一个新的 Promise,里面有一个 Promise?如果我正确阅读了您的代码,client.connect 也会返回一个承诺
标签: javascript node.js express error-handling promise