为啥不等待函数作为承诺?

Posted

技术标签:

【中文标题】为啥不等待函数作为承诺?【英文标题】: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); ); 【参考方案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
)

【讨论】:

以上是关于为啥不等待函数作为承诺?的主要内容,如果未能解决你的问题,请参考以下文章

异步函数 - 等待不等待承诺

为啥等待后的代码没有立即运行?它不应该是非阻塞的吗?

等待从父函数解决的承诺

打字稿 - 在函数返回之前等待承诺解决

承诺等待得到解决而不返回

等待多个承诺完成