如何在jquery中对loadedmetadata使用async和await来同步加载?

问题描述 投票:0回答:1

我想使用jquery通过await同步获取音频持续时间。 我想按此顺序获取警报消息:

   111 
   222 leng=1.549188
   333 duration=1.549188 
   444 

但是我得到了异步订单:

   111 
   333 duration=9999 
   444 
   222 leng=1.549188 

如何解决?

var duration = 99999 ; 

async function getAudioUrlDuration(src, callBackFun) {
    var audio = new Audio();
    audio.src = src;
    await $(audio).on("loadedmetadata", function(){
        callBackFun( audio.duration );
        duration = audio.duration ;
    });
}
function callBackFun3(leng){ 
    alert('222 leng='+leng) ; 
}
var src = "https://www.w3schools.com/tags/horse.mp3" ;

async function aaa(){
  alert(111);
  await getAudioUrlDuration(src, callBackFun3 )  ; 
  alert( '333  duration='+duration ) ; 
  alert(444);
} 
 
 aaa();
javascript jquery async-await synchronization
1个回答
0
投票

问题是

on
jQuery
函数不会向
await
返回一个 Promise,您需要将
getAudioUrlDuration
函数返回一个 Promise,该 Promise 将在
on
回调成功时得到解决。

var duration = 99999; 
async function getAudioUrlDuration(src) {
    var audio = new Audio();
    audio.src = src;
    // Return a promise that resolves when the loadedmetadata event is triggered
    return new Promise((resolve) => {
        $(audio).on("loadedmetadata", function(){
            duration = audio.duration;
            resolve(audio.duration);
        });
    });
}

function callBackFun3(leng){ 
    alert('222 leng=' + leng); 
}

var src = "https://www.w3schools.com/tags/horse.mp3";

async function aaa(){
    alert(111);
    var audioDuration = await getAudioUrlDuration(src);
    callBackFun3(audioDuration);  
    alert('333 duration=' + duration); 
    alert(444);
}

aaa();
© www.soinside.com 2019 - 2024. All rights reserved.