jQuery承诺:立即调用回调函数

jQuery承诺:立即调用回调函数,jquery,promise,video.js,Jquery,Promise,Video.js,我使用functiondoPlaySequence播放几个视频,然后使用functiondrawConfig显示一张图片。我这样写代码: 函数等待(dtd){ var dtd=$.Deferred(); setTimeout(函数(){ doPlaySequence(); dtd.resolve(); }, 0); 返回dtd.promise(); } wait().then(drawConfig)要仅在视频完成后运行drawConfig函数,您需要从视频的end事件处理程序中调用该函数,或者

我使用function
doPlaySequence
播放几个视频,然后使用function
drawConfig
显示一张图片。我这样写代码:

函数等待(dtd){
var dtd=$.Deferred();
setTimeout(函数(){
doPlaySequence();
dtd.resolve();
}, 0);
返回dtd.promise();
}

wait().then(drawConfig)
要仅在视频完成后运行
drawConfig
函数,您需要从视频的
end
事件处理程序中调用该函数,或者创建在该事件中解析的承诺。试试这个:

function doPlaySequence()
{
  var deferred = $.Deferred();

  // your code...

  var opplay = document.createElement('video');
  // opplay logic here...

  opplay.addEventListener("ended", function(e) {
    // video ended logic here...

    deferred.resolve();
  }

  return deferred;
}

doPlaySequence().then(drawConfig);

您将看到,
doPlaySequence
函数现在返回延迟值,该值仅在视频停止播放后解析。然后,将依次调用
drawConfig

video.js播放器有一个结束事件,您应该收听该事件,您应该在该事件之后解析您的延迟对象

在doPlaySequence()中

您可能需要将dtd对象传递给doPlaySequence,或者只是在doPlaySequence中创建它,因为它的唯一目的是等待视频完全播放


设置超时将不起作用。

这是预期的行为-您已将超时设置为
0
,因此它会立即执行。您希望发生什么?@Rorymcrossan我希望在doPlaySequence用完(视频播放到结尾)后调用drawConfig,但它会立即被调用。请您将
doPlaySequence()
的代码添加到您的问题中。@Rorymcrossan没关系,谢谢。是的,我知道了。我应该在整个视频结束时立即解决它“else”分支。我学习了除了视频和图片外,代码是按顺序执行的。为了使代码简洁,我必须使用闭包,而不是将整个视频代码写入等待函数?
 myPlayer.on('ended', function() {
    dtd.resolve();
 });