【问题标题】:async / await function and return valueasync / await 函数和返回值
【发布时间】:2021-06-06 09:54:39
【问题描述】:

从最高级别开始,我正在尝试将 Blob 传递给将转录数据并返回转录本的函数。我正在努力使流程的异步部分正确排列。任何见解将不胜感激。

我正在使用的两个文件如下。在 record.jsx 文件中,我正在调用 googleTranscribe 函数(位于第二个文件中)来完成转录工作并希望返回转录本。这就是我遇到问题的地方 - 我可以获得成绩单但不能将其作为值返回。我知道我在使用 async/await/promises 时做错了,我只是无法弄清楚我做错了什么。

record.jsx

import React from "react";
import googleTranscribe from '../../functions/googletranscribe.js';
const audioType = 'audio/wav';

class Record extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      recording: false,
      audioUrl: '',
      audios: [],
    };
  }

   componentDidMount() {

    const player = document.getElementById('player');
    const stopButton = document.getElementById('stop');
    const startButton = document.getElementById('start');

    const initalizeRecorder = function(stream) {

      if (window.URL) {
        player.srcObject = stream;
      } else {
        player.src = stream;
      }

      const options = {mimeType: 'audio/webm'};
      let recordedChunks = [];
      const mediaRecorder = new MediaRecorder(stream, options);

      mediaRecorder.addEventListener('dataavailable', function(e) {
        if (e.data.size > 0) {
          recordedChunks.push(e.data);
        }
      });

      mediaRecorder.addEventListener('stop', function() {
        const audioData = recordedChunks;

        // convert saved chunks to blob
        const blob = new Blob(audioData, {type: audioType});

        // generate video url from blob
        const audioUrl = window.URL.createObjectURL(blob);
        
        googleTranscribe(blob)
          .then((response) => {
            console.log('transcript: ' + response);
          }).catch((error) => {
            console.log('error: ' + error);
          });

      });

      startButton.addEventListener('click', function() {
        mediaRecorder.start(1000);
      });

      stopButton.addEventListener('click', function() {
        mediaRecorder.stop();
      });

    };

    navigator.mediaDevices.getUserMedia({ audio: true, video: false })
      .then(initalizeRecorder);
  
  render() {
    
    return (
      <section>
        <button id="start">Record</button>
        <button id='stop'>Stop</button>
      </section>
    );
  }
}

export default Record;

googletranscribe.jsx

import axios from 'axios';

const googleTranscribe = async (audioBlob) => {

  const apiUrl = "http://localhost:8080/api/google-transcribe";
  
  const url = encodeURI(apiUrl); 

  // Send blob to the server
  const formData = new FormData();
  formData.append('file', audioBlob, 'blobby.wav');
  
  var config = {
    method: 'post',
    url: url,
    headers: { "Content-Type": "multipart/form-data" },
    data : formData,
  };

  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;

【问题讨论】:

  • 尽管尝试使用async/await,但您没有使用await 而不是.then()。因此你的return 不起作用
  • 你应该return axios(config).then...,它会返回承诺。

标签: javascript reactjs async-await promise


【解决方案1】:

问题出在第二个文件中。你的 Axios 行应该这样修改:

return axios(config)
  .then(function (res) {
    console.log('AXIOS success');
    console.log(res);
    return res.data;
  })
...

axios 调用在内部返回该值,但您永远不会从 googletranscribe 返回它

【讨论】:

  • 这可能会有所帮助。但请记住,为了“获取”返回值 res,您需要等待异步函数 googleTranscribe() 解析,例如:googleTranscribe(audioBlob).then(res=&gt;do_something_with(res));
【解决方案2】:

让我给你一些关于 async-await 的上下文 async 关键字将方法转换为异步方法,这允许您在其主体中使用 await 关键字。应用 await 关键字时,它会暂停调用方法并将控制权交还给调用者,直到等待的任务完成。了解更多信息的最佳地点是Here

【讨论】:

  • 很好,感谢您的上下文;绝对让我更清楚。
猜你喜欢
  • 2021-08-06
  • 2019-03-01
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
相关资源
最近更新 更多