我如何使用jQuery.Deferred对象等待异步函数调用完成?

Hri*_*sto 4 ajax jquery plupload jquery-deferred

我在表单中使用Plupload文件上传器.我想自定义它,以便在提交表单时,即单击"提交"按钮时,首先发生的是文件上载,然后是表单的提交.

据我所知,我可能错了,但似乎调用uploader.start()是异步函数调用.因此,目前,上传将开始,表单将在文件上传之前提交.问题是我无法控制这个函数调用.

我最近读到了关于jQuery 1.5新版本和新的Deferred Object,看起来这有可能帮助我解决这个问题.有没有办法等待异步函数调用完成其工作,然后在调用后继续执行代码.所以我正在寻找类似下面的伪代码...

var uploader = $('#plupload_container').pluploadQueue();

$('#submitButton').click(function() {

   // if there are files to be uploaded, do it
   if (uploader.files.length > 0) {

      // make the call and wait for the uploader to finish
      uploader.start();
      while ( the uploading is not done ) {
         wait for the uploader to finish
      }

      // continue with submission
   }
});
Run Code Online (Sandbox Code Playgroud)

有没有办法"等待" uploader.start()完成,基本上在click事件处理程序上暂停,以便可以先上载所有文件,然后其余的click事件处理程序可以完成执行?我尝试了以下内容,但在文件上传之前打印了"完成"...

$.when(uploader.start()).then(function () {
   console.log("done")
});
Run Code Online (Sandbox Code Playgroud)

另一个有用的信息...我可以将某些事件绑定到此uploader对象实例,例如"UploadProgress"或"UploadComplete".例如,我可以以某种方式使用延迟对象来捕获"UploadComplete"事件触发的时间吗?是否有AJAX-y方式来做到这一点?

谢谢.

Ray*_*nos 5

你的问题是,虽然uploader.start为代码工作异步,uploader.start但必须返回一个jquery $.deferred对象.

来自您的上传器插件的最新资源:

/**
 * Starts uploading the queued files.
 *
 * @method start
 */
start : function() {
    if (this.state != plupload.STARTED) {
        this.state = plupload.STARTED;
        this.trigger("StateChanged");
        uploadNext.call(this);
    }
},
Run Code Online (Sandbox Code Playgroud)

所以它不会返回延迟对象.而在uploadNext函数中有这行代码:

this.trigger("UploadComplete", files);

所以我们只需要绑定到你的上传器,

uploader.bind("UploadComplete", function(files) {
    // your code
});
Run Code Online (Sandbox Code Playgroud)

我从来没有使用过该插件,但这应该可行.祝好运.

如果你必须使用延迟,那么你总是可以像这样的伪代码:

var uploader = $('#plupload_container').pluploadQueue();
var def = $.Deferred();
uploader.bind("UploadComplete", function(files) {
    def.resolve(files);
});
$('#submitButton').click(function() {
   if (uploader.files.length > 0) {
      uploader.start();

      def.done(function(files) {
          def = $.Deferred(); // reset the deferred object.
          // rest of your click handler.
      });

   }
});
Run Code Online (Sandbox Code Playgroud)