1

I'm trying to upload multiple attachments. First I'm getting attachments from user interface, then I'm converting them into JSON , then I need to make a server call. In this I'm using FileReader.

        //showing ajax loader
        component.set("v.showLoadingSpinner", true);

       //getting attached files
        var files = component.find("fileId").get("v.files");
        var details = {};    //JS Object need to send server
        details.files = [];

        for (var i = 0; i < files.length; i++) 
        {      
            (function(file) {
                var name = file.name;
                var reader = new FileReader(); 
                reader.fName = files[i]['name'];
                reader.fType = files[i]['type'];
                reader.i = i;
                reader.onload = function(e) {
                    var fileContents = reader.result;
                    var base64 = 'base64,';
                    var dataStart = fileContents.indexOf(base64) + base64.length;
                    fileContents = fileContents.substring(dataStart);
                    var startPosition = 0;
                    var endPosition = Math.min(fileContents.length, startPosition + 750000);
                    var getchunk = fileContents.substring(startPosition, endPosition);
                    var fDetails = {};
                    fDetails.fileName = reader.fName;
                    fDetails.base64Data = encodeURIComponent(getchunk);
                    fDetails.contentType = reader.fType;
                    details.files.push(fDetails);

                }
                reader.readAsDataURL(file);
            })(files[i]);

     // I want to make a server call here with data in "details" object.
   console.log(details);   

But I'm not getting data in above console log.

Please help me to achieve this.

Manoj
  • 289
  • 1
  • 2
  • 11
  • cause calling an ajax is asynchronous so it's not like console line get called after they did their job. – nullqube Oct 24 '17 at 13:42
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ideaboxer Oct 24 '17 at 13:58

1 Answers1

1

You can use promises :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://davidwalsh.name/promises

https://developers.google.com/web/fundamentals/primers/promises

Also jQuery provide $.when() function :

https://api.jquery.com/jquery.when/

And with promisejs you can do something like this :

function readJSON(filename){
  return new Promise(function (fulfill, reject){
    readFile(filename, 'utf8').done(function (res){
      try {
        fulfill(JSON.parse(res));
      } catch (ex) {
        reject(ex);
      }
    }, reject);
  });
}
nullqube
  • 2,959
  • 19
  • 18