RickyAYoder
RickyAYoder

Reputation: 991

How to return value from a callback within a function?

I'm trying to make a simple function to take a JavaScript FileEntry and "convert" it into a JavaScript File object. I have the basic function here:

function fileEntrytoFile(e){
  var f = 0;

  e.file(function(file){
    f = file;
  });
  return f;
}

f is still 0 when it is returned. How can I return the File object that is being generated by the callback function within?

Upvotes: 2

Views: 106

Answers (1)

user663031
user663031

Reputation:

You will need to return a promise, since FileEntry.file is asynchronous:

function fileEntrytoFile(e){
  return new Promise((resolve, reject) => e.file(resolve, reject));
}

fileEntrytoFile(fileEntry) . then(file => console.log(file.name));

The above uses ES6 arrow functions and ES6 promises.

Upvotes: 7

Related Questions