Home > database >  Why is a function not awaited as a promise?
Why is a function not awaited as a promise?

Time:12-03

I have a component MicButtons.js which exports a promise

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
  }
}

And when I try to use it in another component, await doesn't work and alert shows "undefined"

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>

This is how MyButton component looks like:

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

CodePudding user response:

Taking a guess here but it looks like you want to promis-ify the Voice.onSpeechResults callback.

Have your MicButton function return a promise that resolves with the result you want

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
})
  • Related