Search code examples
jqueryfile-uploadpromiseblueimp

Wait till the jquery function returns value


I'm using jQuery Blueimp file upload and trying to get the uploaded file json in a variable. I'm calling the function as:

var fileoutput = attachfile(fileobject, ['xlsx','zip'],"tmp");

This will call the function :

function attachfile(fileobject, allowedfiletypesarray, destinationfolderpath) {
    var allowedFileTypes; 
    allowedFileTypes = allowedfiletypesarray.join('|');
    allowedFileTypes = "/\.("+allowedFileTypes+")$/i";

    $(fileobject).fileupload({
        add: function(e, data) {        
            if(data.originalFiles[0]['type'].length && !allowedFileTypes.test(data.originalFiles[0]['type'])) { 
                $('#fileerror').html('Not an accepted file type'); // show error message
                return false;
            } 
            data.submit();
        },
        url: "uploadcsv.php", 
        dataType: 'text',
        acceptFileTypes : allowedFileTypes,
        formData: {"upload_url":destinationfolderpath},
        done: function (e, data) {
            var fileuploadresult = data.result;
            fileuploadresult = JSON.parse(fileuploadresult); 
            console.log(fileuploadresult);
            return fileuploadresult;
        },
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');   
}

Now the issue is,

var fileoutput = attachfile(fileobject, ['xlsx','zip'],"tmp");
console.log(fileoutput);

This is returning undefined. And I'm not getting the return from attachfile(). console.log(fileuploadresult); inside attachfile() is printing the uploaded file details correctly.

So I tried adding promise like :

function promisefunction() {
  return new Promise(function (resolve, reject) {
    resolve( attachfile(fileobject, ['xlsx','zip'],'tmp') );
  });
}

promisefunction()
.then(value => {
    console.log("value : "+value);
})
.catch(err =>{
    // handle error
});

But this is also returning undefined result before file is uploaded.

Can anyone help me to solve this. Thanks in advance.


Solution

  • The issue is because the Promise you return is not tied to the AJAX request that blueimp is making.

    The simplest way to achieve what you require is to provide a callback function to your attachfile() call and then invoke that within done(), something like this:

    var fileoutput = attachfile(fileobject, ['xlsx', 'zip'], 'tmp', function(value) {
      console.log('value : ' + value); 
    });
    
    function attachfile(fileobject, allowedfiletypesarray, destinationfolderpath, callback) {
      var allowedFileTypes = "/\.(" + allowedFileTypes + ")$/i";
    
      $(fileobject).fileupload({
        add: function(e, data) {
          if (data.originalFiles[0]['type'].length && !allowedFileTypes.test(data.originalFiles[0]['type'])) {
            $('#fileerror').html('Not an accepted file type');
            return false;
          }
          data.submit();
        },
        url: "uploadcsv.php",
        dataType: 'text',
        acceptFileTypes: allowedFileTypes,
        formData: {
          "upload_url": destinationfolderpath
        },
        done: function(e, data) {
          var fileuploadresult = JSON.parse(data.result);
          callback && callback(fileuploadresult); // invoke the callback here
        },
      }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
    }