jQuery承诺对象

时间:2018-11-24 23:12:34

标签: jquery web

function uploadfiles(inputcontrol){ 
   //here the function takes all the files of an input files
   //for each inputcontrol.files[i]
   //createObject(inputcontrol.files[i]);
}

function createObject(files){ 
  //this function creates an object with each one of them the files 
  //are processed and loaded in a web service whit AJAX
}

when(uploadfiles()).then(alert('All files uploaded'));

运行此脚本时,警报会立即显示,它不会等待文件正确上传。我应该如何运行$。什么时候?

1 个答案:

答案 0 :(得分:1)

我更新了您的clupload类,以便它可以使用Deferred对象读取文件,因为我们现在可以链接读取文件然后上载的过程。

我还更改了getBase64函数,使其返回了Deferred对象,这样我们以后可以使用donefail方法。

代码如下:

class clupload {
  constructor(file, Ticket) {
    this.f = file;
    this.t = Ticket;
  }

  readFile () {
    var dfd = $.Deferred();
    var reader = new FileReader();
    reader.onload = function(e) {
      dfd.resolve(e.target.result);
    };
    reader.readAsDataURL(this.f);
    return dfd.promise();
  }

  procesar() {
    var tt = this.t;
    var nombre = this.f.name;
    var user = $('#loginUsrApp').val();
    return this.readFile().then(function (salida) {
      return $.ajax({
        type: "POST",
        url: "WebService.asmx/SubirArchivo",
        data: "{T:'" + tt + "',b64:'" + salida + "',N:'" + nombre + "',U:'" + user + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json"
      })
    });
  }
}

function getBase64(f, T) {
  var files = document.querySelector(f).files;
  var uploads = files.map(function (file) {
    var upload = new clupload(file, T);
    return upload.procesar();
  });
  return $.when.apply($, uploads);
}

现在您只需要这样称呼它即可:

getBase64('#upload1', r.d).done(function() {
  alert('Guardado');
}).fail(function () {
  alert('Error');
});