简体   繁体   English

firebase 云函数中的 Promises 错误处理

[英]Error handling with Promises in firebase cloud functions

I am pretty new to firebase cloud functions and javascript as a whole and i'm trying to get the hang of error handling within cloud functions.我对 firebase 云函数和 javascript 作为一个整体非常陌生,我正在尝试掌握云函数中错误处理的窍门。 I wrote a function that simply takes data from a firestore document and updates another one.我写了一个 function,它只是从一个 firestore 文档中获取数据并更新另一个文档。 However when I test error scenarios the rejection isn't properly handled.但是,当我测试错误场景时,拒绝没有得到正确处理。 The code below shows the function.下面的代码显示了 function。 Please what am i doing wrong??请问我做错了什么??

exports.testFunction = functions.firestore.document('test/{docID}').onCreate(async(snap, context)=>{
const data = snap.data();
const name = data.name;
const age = data. age;
const id = context.params.docID;
return new Promise(async(res, rej)=>{
  try{
       await firestore.collection('testResults').add({
         'name': name,
         'age': age
        }); 
       await firestore.collection('test').doc(id).delete();
       res();
  }catch(e){
   console.log(e);
   rej();
  }
 });
});

Firstly, there is rarely a reason to use new Promise in JavaScript when you have async/await available with functions that already return promises.首先,很少有理由在 JavaScript 中使用new Promise ,当您有 async/await 可用的功能时,这些功能已经返回承诺。 You should just let the existing promises returned by Firestore reject normally - there is no need to capture their errors if all you intend to do is log them.您应该让 Firestore 返回的现有承诺正常拒绝 - 如果您只想记录它们,则无需捕获它们的错误。 Cloud Functions will log the rejected promises. Cloud Functions 将记录被拒绝的承诺。

All you really need to do is this:您真正需要做的就是:

const data = snap.data();
const name = data.name;
const age = data. age;
const id = context.params.docID;
await firestore.collection('testResults').add({
    'name': name,
    'age': age
}); 
await firestore.collection('test').doc(id).delete();

If you do need to capture the rejected promises from Firestore for whatever reason, you can use try/catch and just return a new rejection to fail the function correctly:如果您出于某种原因确实需要从 Firestore 捕获被拒绝的承诺,您可以使用 try/catch 并返回一个新的拒绝以正确地使 function 失败:

try {
    await firestore.collection('testResults').add({
        'name': name,
        'age': age
    }); 
    await firestore.collection('test').doc(id).delete();
}
catch (e) {
    return Promise.reject(e);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM