Firebase Cloud Functions/每个then()应该返回一个值或抛出promise/always-return
问题描述:
我一直遵循关于承诺的官方Firebase教程( https://www.youtube.com /watch?v = 7IkUgCLr5oA ),但就我而言,我无法使其正常工作.
I was following the official firebase tutorial on promises (https://www.youtube.com/watch?v=7IkUgCLr5oA) but in my case, I cannot make it work.
const promise = userRef.push({text:text});
const promise2 = promise.then((snapshot) => {
res.status(200).json({message: 'ok!'});
});
promise2.catch(error => {
res.status(500).json({message: 'error'});
});
我做错了什么?万一出现问题,每个then()应该都有其响应,但这就是为什么我要编写promise2 catch的原因.
What am I doing wrong? Each then() should have its response in case something goes wrong, but that is why I am writing the promise2 catch.
答
只需在发送响应之前添加return
.
Just add the return
before sending the response.
const promise = userRef.push({text:text});
const promise2 = promise.then((snapshot) => {
return res.status(200).json({message: 'ok!'});
});
promise2.catch(error => {
return res.status(500).json({message: 'error'});
});
您还可以按如下方式链接承诺:
Also you can chain the promises as follows:
return userRef.push({text:text})
.then((snapshot) => {
return res.status(200).json({message: 'ok!'});
}).catch(error => {
return res.status(500).json({message: 'error'});
});