Returning an object with a promise (resolve, reject)

Viewed 122

I have made a promise, from which I want to convert a webkitGetAsEntry fileobject to a regular File object.

var getAsFile = async function(fileEntry) {
    try {
        return new Promise((resolve, reject) => fileEntry.file(resolve, reject));
    } catch (err) {
        console.log(err);
    }
}

However, after alot of changes to my code, I would really want to return an object in which I have a path to the file as well. I.e.

var getAsFile = async function(fileEntry) {
    try {
        return new Promise((resolve, reject) => return { 'file': fileEntry.file(resolve, reject), 'filepath': fileEntry.fullPath};);
    } catch (err) {
        console.log(err);
    }
}

When the following promise is resolved, only the file is returned and not the object.

getAsFile(entries[i]).then(function (file) {
    //Can only get the file, and not file.filepath
})

What fundamental knowledge about promises am I missing here, and how do I achieve returning an object with file and filepath?

1 Answers

You need to pass the object to the resolve function:

var getAsFile = function(fileEntry) {
    return new Promise((resolve, reject) => fileEntry.file(
        file => resolve({file, filepath: fileEntry.fullPath}),  
        reject
    ));
}

Note that it is not necessary to declare that function as async since you return a promise and don't use await.

The error handling should happen at the place where this function is called.

Related