【问题标题】:Why is a function not awaited as a promise?为什么不等待函数作为承诺?
【发布时间】:2022-01-09 09:33:11
【问题描述】:

我有一个导出承诺的组件 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

【问题讨论】:

  • MicButton 不返回任何内容
  • 您的MicButton() 函数没有返回值,因此您的命令未定义。 Voice.onSpeechResults = ... 为这个属性分配了一个函数,但你没有在这里调用它。
  • JSON.parse 不是异步等待没有意义。
  • export const MicButton = async () =&gt; { return new Promise((resolve) =&gt; { Voice.start('en-US') Voice.onSpeechResults = async (res) =&gt; { res = await JSON.parse(JSON.stringify(res)).value[0] resolve(res); } }});}

标签: javascript react-native async-await promise


【解决方案1】:

在这里猜测一下,但看起来你想promis-ify Voice.onSpeechResults回调。

让您的 MicButton 函数返回一个承诺,该承诺会以您想要的结果解决

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

【讨论】:

    猜你喜欢
    • 2019-04-29
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2018-02-03
    • 2018-07-27
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    相关资源
    最近更新 更多