RickyAYoder RickyAYoder - 5 months ago 12
Javascript Question

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?

Answer

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.