【问题标题】:Typescript promise must be handled properly打字稿承诺必须正确处理
【发布时间】:2020-03-12 19:33:47
【问题描述】:

我有以下内容来更新我的 Firestore 文档。但是有一个错误说必须正确处理promise。我已经在我的函数中添加了 try catch..谁能告诉我还有什么遗漏的?

export const updateCustomer = functions.https.onRequest(async (req, resp) => {
    try
    {
            await db.collection('Users').where('CompanyId', '==', req.body.CompanyId)
            .where('CustomerId', '==', req.body.CustomerId)
            .get()
            .then(snapshot => {   
                 snapshot.forEach(doc => 
                     {
                         db.collection('Users').doc(doc.id).update(
                             {
                                 CustomerName : req.body.CustomerName,
                                 MobileNo : req.body.MobileNo,
                                 DOB: req.body.DateOfBirth,
                                 Email : req.body.Email,
                                 PreferredLanguage: req.body.PreferredLanguage
                             }
                         )
                     })
            })
            .catch(error => resp.status(500).send(error));   



       resp.status(200).send(req.body);
    }
    catch(error)
    {
       console.error(error);
       resp.status(500).send({ Message: error, StatusCode: '500', Status: 'Error'});
    }
})

【问题讨论】:

    标签: typescript promise google-cloud-firestore


    【解决方案1】:

    db.collection('Users').doc(doc.id).update() 返回一个承诺,而您的代码忽略了它。 HTTP 类型的函数只应在所有异步调用完全完成后返回结果。对整个事情进行尝试/捕捉将无济于事。

    【讨论】:

    • 您有什么建议可以修改我的代码吗?
    • 将所有的 Promise 收集到一个数组中,并在它们全部解析后使用 Promise.all() 运行一些代码。
    • 照@DougStevenson 说的做,但也不要忘记从你的 .then() 返回聚合的承诺,不要将 async/await 与 .then() 语法混合。从您现在的位置开始,更简单的选择可能是清除 async/await 并以 return db.collection()......get().then().then().catch(); 结束,最后的捕获是您唯一需要的。
    猜你喜欢
    • 2020-02-19
    • 2021-08-21
    • 2019-08-21
    • 2020-11-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2020-03-10
    相关资源
    最近更新 更多