具有延迟对象的构造函数

constructor with deferred object

本文关键字:构造函数 对象 延迟      更新时间:2023-09-26

我正在尝试充分利用$。Deferred(( 来控制异步函数的结束。我还想要从函数返回的一些信息。

我设置了这样的东西

var VideoInputOk2Start = new VideoInputStart();
    $.when(VideoInputOk2Start.Control).done(function () { console.log("SetUpVideoOK") });

    function VideoInputStart() {
        this.Control = $.Deferred();
        this.Ok = false;
if ( videoInput.paused == true ) {
    videoInput.play();
    this.Control.resolve();
    this.Ok = true;
}
    }

这种方法正确吗?还是有更简单的东西?或者我是否对VideoInputOk2Start.Control进行了错误检查,因为它可能尚未由构造函数创建。一些竞争条件错误(无论如何,它令我惊讶(

谢谢

在您列出的代码中,您的承诺是在完成任何工作之前解决。 据推测,某些异步函数要么采用回调函数,要么返回承诺。 您的承诺的解析器正在运行,就好像代码会等待不会发生的"异步"函数一样(除非您使用生成器或某些此类方法(。 相反,您可以在下面看到一些您可以使用的结构。

function someConstructor(url) {
  this.OK = false; // This is somewhat unnecessary with promises as you can check the state of a promise
  this.Control = fetch(url) // Async function which returns promise
    .then(function(res) { // Resolver function
      this.OK = true; // Set OK after promise is completed
    }.bind(this)); // bind 'this' to anonymous function
  console.log('Constructor has completed running');
}
var x = new someConstructor('http://i.imgur.com/63xpOZkb.jpg');
x.Control.then(function(res) {
  console.log("I am running only after async work is completed");
  document.write('completed download');
});
console.log("I am running after declaration of resolution function");

运行上述代码时,请查看使用 console.log 写入控制台的语句。 解析器函数中包含的代码仅在承诺完成后运行。 这是您将更改某些状态的地方。 如果您注意到代码底部的语句在异步工作完成之前运行。 这说明了为什么你不能像你一样让你的代码(使用 .resolve(( 在你的"异步"工作后立即运行(。