为什么不等待功能作为承诺?

Why is a function not awaited as a promise?

我有一个导出承诺的组件MicButtons.js

import Voice from 'react-native-voice'
export const MicButton = async () => {
  Voice.start('en-US')
  Voice.onSpeechResults = async (res) => { 
    res = await JSON.parse(JSON.stringify(res)).value[0] 
    return res
  }
}

当我尝试在另一个组件中使用它时,等待不起作用并且警报显示“未定义”

import MyButton from '../components/MyButton';
import { MicButton } from '../components/MicButton';
//...
<MyButton h="80%" w="50%" srcImg={mic} func={async() => {
  let command = await MicButton()
  alert(command)           
}}></MyButton>

这是 MyButton 组件的样子:

import React from 'react';
import PropTypes from 'prop-types'
import { Text, View, TouchableOpacity, ImageBackground } from 'react-native';

const MyButton = ({ text="", h, w, srcImg, func=()=>{} }) => {

  return (
    <View style={{height: h, width: w}}>
      <TouchableOpacity style={{ height: '100%', width: '100%'}} onPress={func}>
        <ImageBackground source={srcImg} style={{flex: 1}}>

          <Text>{text}</Text>

        </ImageBackground>       
      </TouchableOpacity>
    </View>
  )
}

MyButton.PropTypes = {
  text: PropTypes.string,
  h: PropTypes.number,
  w: PropTypes.number,
  srcImg: PropTypes.object,
  func: PropTypes.func
}

export default MyButton

在这里进行猜测,但看起来您想 promis-ify Voice.onSpeechResults回调。

让你的 MicButton 函数 return 有一个承诺,可以解决你想要的结果

export const MicButton = () => new Promise((resolve, reject) => {
  Voice.start('en-US')
  Voice.onSpeechResults = (res) => { 
    resolve(res.value[0])
  }
  Voice.onSpeechError = reject
}).finally(() => {
  Voice.removeAllListeners() // clean up
})