marcelo2605
marcelo2605

Reputation: 2794

Problem using promise and await on a Vue method

I'm running a function in mounted() to grab files from my Dropbox account using a promise. On success of this promise, I loop all files and run another promise function to grab additional info of each files and add it to object.

data () {
    return {
        results: [],
        dropbox: [],
    }
},
mounted() {
    dropbox.filesListFolder({path: '/wallpapers'}).then(this.successHandler)
    this.dropbox = dropbox
},
methods: {
    successHandler (response) {
        const files = response.entries;
        async function processArray(files) {
            for (const item of files) {
                item['meta'] = await this.getFileInfo(item.id);
            }
        }
        processArray(files);
        this.results = files;
    }
    getFileInfo (id) {
        this.dropbox.filesGetMetadata({
            path: id,
        })
        .then(this.successFileInfo)
    },
    successFileInfo (response) {
        return response; 
    }
}

But this return an error:

Cannot read property 'getFileInfo' of undefined

Upvotes: 0

Views: 131

Answers (2)

gleam
gleam

Reputation: 870

You have a scope-problem - wrong this:

    let vm = this;
    async function processArray(files) {
        for (const item of files) {
            item['meta'] = await vm.getFileInfo(item.id);
        }
    }

Or you can do:

processArray.bind(this)(files);

UPD (from comments):

You forgot return in getFileInfo-method

getFileInfo (id) {
    return this.dropbox.filesGetMetadata({
        path: id,
    })
    .then(this.successFileInfo)
}

Upvotes: 3

James Coyle
James Coyle

Reputation: 10398

When you call item['meta'] = await this.getFileInfo(item.id);, this refers to the scope of the processArray function and not the vue component.

If I'm not mistaken, you should just be able to do:

async successHandler (response) {
    const files = response.entries;
    for (const item of files) {
        item['meta'] = await this.getFileInfo(item.id);
    }
    processArray(files);
    this.results = files;
}

Upvotes: 1

Related Questions