You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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语法混用了。

  1. 用await调用axios.post时,已经能直接拿到请求的响应结果,但你额外链式添加了then回调——此时await会等待整个then链执行完毕,response变量其实就是then里返回的{'imageURL':response.data.output}对象,但你的函数最后没有把这个response给return出去!所以Firebase可调用函数默认返回undefined,也就是你看到的空值。
  2. 另外你的catch回调只打印错误,没有抛出异常,一旦请求出错,函数也会默默返回undefined,给排查问题增加了障碍。

正确写法

直接用await获取响应后返回结果,不用嵌套then,代码更清晰,也不会丢失返回值:

const response = await axios.post('https://..', formData, {
  
  headers: formData.getHeaders()
})

return {'imageURL':response.data.output};

内容的提问来源于stack exchange,提问作者Ozgur Sahin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:55:17