async/await调用谷歌语音转写函数无法正常获取返回值问题求助
问题核心原因
你定义的googleTranscribe异步函数没有返回Promise对象:
- 你在函数内部调用了axios发起异步请求,但没有把这个axios实例(本身是Promise)return出去
- async函数如果没有显式return值,默认返回的是resolve为undefined的Promise,所以调用方的.then拿到的永远是undefined
修复方案
第一步:修改googletranscribe.js
两种写法选一种即可:
写法1:匹配async语法,用await接收结果
import axios from 'axios'; const googleTranscribe = async (audioBlob) => { const apiUrl = "http://localhost:8080/api/google-transcribe"; const url = encodeURI(apiUrl); // 构造表单数据 const formData = new FormData(); formData.append('file', audioBlob, 'blobby.wav'); const config = { method: 'post', url: url, headers: { "Content-Type": "multipart/form-data" }, data : formData, }; try { const res = await axios(config); console.log('AXIOS success'); console.log(res); return res.data; } catch(err) { console.log('AXIOS error'); console.log(err.message); return 'AXIOS we found an error'; } } export default googleTranscribe;
写法2:保留.then链式调用,返回axios实例
import axios from 'axios'; const googleTranscribe = (audioBlob) => { const apiUrl = "http://localhost:8080/api/google-transcribe"; const url = encodeURI(apiUrl); // 构造表单数据 const formData = new FormData(); formData.append('file', audioBlob, 'blobby.wav'); const config = { method: 'post', url: url, headers: { "Content-Type": "multipart/form-data" }, data : formData, }; // 这里必须加return把Promise返回给调用方 return axios(config) .then(function (res) { console.log('AXIOS success'); console.log(res); return res.data; }) .catch(function (err) { console.log('AXIOS error'); console.log(err.message); return 'AXIOS we found an error'; }); } export default googleTranscribe;
第二步:可选优化record.jsx调用逻辑
你当前的调用写法是符合规范的,修改完googleTranscribe之后,then里就能正常拿到返回的转写结果,不需要额外调整。如果要统一异步写法,也可以把stop事件的回调改成async函数,用await接收结果:
mediaRecorder.addEventListener('stop', async function() { const audioData = recordedChunks; const blob = new Blob(audioData, {type: audioType}); const audioUrl = window.URL.createObjectURL(blob); try { const response = await googleTranscribe(blob); console.log('transcript: ' + response); } catch(error) { console.log('error: ' + error); } });
内容的提问来源于stack exchange,提问作者John Goodman
相关产品推荐
相关产品推荐

