我想使用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();
问题是
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();