Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is a function not awaited as a promise?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading