Javascript 异步等待承诺不起作用:PromiserResult未定义

Javascript 异步等待承诺不起作用:PromiserResult未定义,javascript,async-await,promise,speech-synthesis,Javascript,Async Await,Promise,Speech Synthesis,我无法使用speechsynthesis框架中的getvoices()函数。 我的基本想法是能够单击文档并能够以西班牙语阅读元素的文本。因此,我尝试使用promise and Wait范例,在根据可用语音列表加载文档时设置语音变量。 我错过了什么?谢谢 var synth=window.speechSynthesis; 函数getVoices(){ 返回新承诺(解决=>{ let voices=speechSynthesis.getVoices() 解决(声音) }) } 异步函数getVoz

我无法使用
speechsynthesis
框架中的
getvoices()
函数。 我的基本想法是能够单击文档并能够以西班牙语阅读元素的文本。因此,我尝试使用promise and Wait范例,在根据可用语音列表加载文档时设置语音变量。 我错过了什么?谢谢

var synth=window.speechSynthesis;
函数getVoices(){
返回新承诺(解决=>{
let voices=speechSynthesis.getVoices()
解决(声音)
})
}
异步函数getVoz(){
const Voces=等待getVoices();
用于(VOCs的voz){
如果(voz.lang==“es”){
返回voz
}
}
}
var voice=getVoz()
函数sayit(){
var div=document.getElementById('main')
var what=div.innerHTML
var hi=新演讲(什么);
高螺距=1;
hi.rate=1;
hi=语音;
合成语音(hi);
}

霍拉·蒙多

我发现至少有3个错误:

  • speechSynthesis.getVoices()
    是一种同步方法,因此封装在承诺中不会产生任何效果。这不是有害的,只是毫无意义
  • var voice=getVoz()
    -在此之后,
    voice
    现在是承诺,而不是结果。但是,您不能在此处添加
    wait
    ,因为您不在异步函数中。您需要使用
    .then()
    和回调
  • hi=语音-这将覆盖整个
    hi
    变量。可能不是我们想要的
我会这样写:


function sayit(){
  var hi = new SpeechSynthesisUtterance(document.getElementById('main').innerHTML);
  hi.pitch = 1;
  hi.rate = 1;
  hi.voice = window.speechSynthesis.getVoices().find(voz => voz.lang == "es-ES");
  window.speechSynthesis.speak(hi);
}

经过更多的阅读,我发现了一些解决我问题的方法:

  • 语音列表异步加载到页面。需要一个onvoiceschanged事件
  • 这段代码有效(wait getVoices()),而前一段代码无效
    const Voces=wait getVoices()
  • 下面的代码可以工作

    let synth = window.speechSynthesis;
    let esp= 0
    const getVoices = () => {
        return new Promise(resolve => {
            let voices = synth.getVoices()
            if (voices.length) {
              resolve(voices)
              return
            }
            const voiceschanged = () => {
              voices = synth.getVoices()
              resolve(voices)
            }
            speechSynthesis.onvoiceschanged = voiceschanged
        })
    }
    
    const getVoz = async () => {
      (await getVoices()).forEach(voice => {
        console.log(voice.name, voice.lang)
        if(voice.lang=="es-ES"){
          esp= voice
        }
      })
    }
    getVoz()
    
    function sayit(){
      let div = document.getElementById('main')
      let what=div.innerHTML
      let hi = new SpeechSynthesisUtterance(what);
      hi.pitch = 1;
      hi.rate = 1;
      hi.voice = esp;
      synth.speak(hi);
    }```