我正在使用 this tutorial作为了解 Dialogflow 和 Firebase 的主要方式,我陷入了以下代码部分:
25 if(action === 'firebase.update'){
26 let userId = 'marc.tuinier';
27 // Check if the user is in our DB
28 admin.firestore().collection('users').where('userId', '==', userId).limit(1).get()
29 .then(snapshot => {
30 let user = snapshot.docs[0]
31 if (!user) {
32 // Add the user to DB
33 admin.firestore().collection('users').add({
34 userId: userId
35 }).then(ref => {
36 sendResponse('Added new user');
37 });
38 } else {
39 // User in DB
40 sendResponse('User already exists');
41 }
42 });
43 }
我遇到了这些错误:
28:9 error Expected catch() or return promise/catch-or-return
31:17 error Each then() should return a value or throw promise/always-return
33:21 error Expected catch() or return promise/catch-or-return
33:21 warning Avoid nesting promises promise/no-nesting
35:29 error Each then() should return a value or throw promise/always-return
我主要想知道如何修复这些错误(也许还有一些 Material ,以便我可以了解更多信息 - 提前致谢!)
最佳答案
就避免嵌套 promise 而言,我建议您研究一下 async/await,给您留下如下内容。然后您可以添加 try/catch block 以进一步调试
if(action === 'firebase.update'){
let userId = 'marc.tuinier';
// Check if the user is in our DB
let snapshot = await admin.firestore().collection('users').where('userId', '==', userId).limit(1).get()
let user = snapshot.docs[0]
if (!user) {
// Add the user to DB
await admin.firestore().collection('users').add({
userId: userId
})
return sendResponse('Added new user');
} else {
return sendResponse('User already exists');
}
}
关于javascript - 如何避免在 Firebase Cloud Functions 中嵌套 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580401/