猿问

获取异步函数的返回值而无需再次调用它

这是代码:


const onStartRecord = async() => {

  try {

    const path = Platform.select({

      ios: `file:///audio/${filenameGenerator}.m4a`,

      android: `file:///audio/${filenameGenerator}.mp4`,

    });

    const audioSet: AudioSet = {

      AudioEncoderAndroid: AudioEncoderAndroidType.AAC,

      AudioSourceAndroid: AudioSourceAndroidType.MIC,

      AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,

      AVNumberOfChannelsKeyIOS: 2,

      AVFormatIDKeyIOS: AVEncodingOption.aac,

    };

    console.log('audioSet', audioSet);

    const uri = await audioRecorderPlayer.startRecorder(path, audioSet);

    audioRecorderPlayer.addRecordBackListener((e: any) => {

      setAudioProp(audioProp => {

        return { ...audioProp,

          recordSecs: e.current_position,

          recordTime: audioRecorderPlayer.mmssss(Math.floor(e.current_position)),

        }

      });


    });


    console.log(`uri: ${uri}`);

    return uri

  } catch (err) {

    console.log(err);

    return;

  }

};


const audioPath = async() => {

  const result = await onStartRecord();

  return result;

}


const onSubmit = async() => {

  const audiopath = await audioPath();

  console.log("this is the audiopath", audiopath)

}

};

当我触发 onSubmit 函数时,我可以得到我想要的,但问题是,它还会再次触发 onStartRecord 函数,这在我的情况下会导致错误,我只想获取 onStartRecord 解析时生成的 uri,但我不'不想再次触发,那么如果我需要使用onSubmit函数并从onStartRecord获取值,我该怎么办?谢谢 !


慕标琳琳
浏览 87回答 1
1回答

神不在的星期二

不应返回uri,而onStartRecord应将其分配给全局变量。然后audioPath()可以返回该变量。let savedAudioPath;const onStartRecord = async() => {  try {    const path = Platform.select({      ios: `file:///audio/${filenameGenerator}.m4a`,      android: `file:///audio/${filenameGenerator}.mp4`,    });    const audioSet: AudioSet = {      AudioEncoderAndroid: AudioEncoderAndroidType.AAC,      AudioSourceAndroid: AudioSourceAndroidType.MIC,      AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,      AVNumberOfChannelsKeyIOS: 2,      AVFormatIDKeyIOS: AVEncodingOption.aac,    };    console.log('audioSet', audioSet);    const uri = await audioRecorderPlayer.startRecorder(path, audioSet);    audioRecorderPlayer.addRecordBackListener((e: any) => {      setAudioProp(audioProp => {        return { ...audioProp,          recordSecs: e.current_position,          recordTime: audioRecorderPlayer.mmssss(Math.floor(e.current_position)),        }      });    });    console.log(`uri: ${uri}`);    savedAudioPath = uri;  } catch (err) {    console.log(err);    return;  }};const audioPath = async () => savedAudioPath;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答