使用Promises时,每个then()应该返回一个值或抛出

从请求返回之前,我有一些异步方法需要等待完成。我正在使用Promises,但我不断收到错误消息:

Each then() should return a value or throw // promise/always-return

为什么这令人高兴?这是我的代码:

router.get('/account', function(req, res) {

var id = req.user.uid

var myProfile = {}

var profilePromise = new Promise(function(resolve, reject) {

var userRef = firebase.db.collection('users').doc(id)

userRef.get()

.then(doc => { // Error occurs on this line

if (doc.exists) {

var profile = doc.data()

profile.id = doc.id

myProfile = profile

resolve()

} else {

reject(Error("Profile doesn't exist"))

}

})

.catch(error => {

reject(error)

})

})

// More promises further on, which I wait for

})

回答:

只要避免Promise构造函数反模式-promise-construction-antipattern-and-how-to-avoid-

it)!如果您不调用resolve而是返回一个值,那么您将需要进行一些操作return。该then方法应该用于链接:

outer.get('/account', function(req, res) {

var id = req.user.uid

var userRef = firebase.db.collection('users').doc(id)

var profilePromise = userRef.get().then(doc => {

if (doc.exists) {

var profile = doc.data()

profile.id = doc.id

return profile // I assume you don't want to return undefined

// ^^^^^^

} else {

throw new Error("Profile doesn't exist")

// ^^^^^

}

})

// More promises further on, which I wait for:

// profilePromise.then(myProfile => { … });

})

以上是 使用Promises时,每个then()应该返回一个值或抛出 的全部内容, 来源链接: utcz.com/qa/402409.html

回到顶部