Firebase可调用函数为何无法在then回调后返回结果?
为何Firebase可调用函数中用then回调返回结果会为空?
我是JavaScript与回调函数的新手,想请教:为何在Firebase可调用函数中,通过then回调返回结果时会返回空值?我推测代码未等待响应完成,但实际上响应中存在data.output变量。
问题代码示例
exports.testApi = functions.https.onCall(async(data, context) => { const formData = new FormData(); formData.append("height", "512"); const response = await axios.post('https://....', formData, { headers: formData.getHeaders() }) .then((response) => { console.log(response.data); return {'imageURL':response.data.output}; }) .catch((error) => { console.log(error) }); } );
问题原因
你犯了一个新手常见的错误:把async/await和Promise的then/catch语法混用了。
- 用
await调用axios.post时,已经能直接拿到请求的响应结果,但你额外链式添加了then回调——此时await会等待整个then链执行完毕,response变量其实就是then里返回的{'imageURL':response.data.output}对象,但你的函数最后没有把这个response给return出去!所以Firebase可调用函数默认返回undefined,也就是你看到的空值。 - 另外你的
catch回调只打印错误,没有抛出异常,一旦请求出错,函数也会默默返回undefined,给排查问题增加了障碍。
正确写法
直接用await获取响应后返回结果,不用嵌套then,代码更清晰,也不会丢失返回值:
const response = await axios.post('https://..', formData, { headers: formData.getHeaders() }) return {'imageURL':response.data.output};
内容的提问来源于stack exchange,提问作者Ozgur Sahin
相关产品推荐
相关产品推荐

