javascript - 如何避免在 Firebase Cloud Functions 中嵌套 promise ?

标签 javascript firebase firebase-realtime-database google-cloud-functions dialogflow-es-fulfillment

我正在使用 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/

相关文章:

javascript - 当循环内的 if 子句中断时,在函数中返回 false

ios - 如何从 Firebase 获取按时间顺序排列的最新帖子?

java - Firebase 检索数组名称和带有身份验证的数组

android - 如何在 android firebase 中应用多个查询?

javascript - 是否可以定义任意对象的 bool 值?

javascript - Angular 浏览器历史记录返回而不重新加载上一页

swift - 按用户名划分的 Firebase 存储镜像

ios - 在同一 Firebase 实例上使用 Firebase 电子邮件链接身份验证登录多个 iOS 应用程序

javascript - jQuery 按钮来检查所有复选框问题

javascript - Firebase WEB - 未发送电子邮件验证。代码有什么问题