MPT
MPT

Reputation: 193

Suggested method to update value in object literal from promise callback

I realize there are probably 10 ways to do this and I typically stumble through some clumsy way to achieve it - however I'd like to get a couple of ideas on "clean" ways to update a value in an object literal from a promise callback.

My current use case is:

let groups2 = {
    groupsList: [],
    updateGroups: () => {
        return axios({
            'url': 'https://gitlab.com/api/v3/groups?per_page=500',
            'method': 'GET',
            'headers': {
                'private-token': GITLAB_API_PRIVATE_TOKEN,
                'cache-control': 'no-cache'
            }
        })
        .then(function (response) {
            console.log(response);
            groups2.groupsList = response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    }
}

This works, however it "feels bad?" to reference "groups2" specifically from inside itself (in the callback in this case). Essentially I want a singleton that can operate on it's own values via functions that may contain promises. I'm looking for better ideas on how to do it.

Upvotes: 1

Views: 817

Answers (1)

mikebridge
mikebridge

Reputation: 4585

Yes, if you use an arrow function inside your object literal, it will not bind "this" to the object. So in es2015 you can use the shorthand syntax for method declarations on object literals. But you will want to use the arrow syntax inside the .then method---there it will bind "this" to the enclosing context:

let groups2 = {
    groupsList: [],
    updateGroups() {    // Change this
        return axios({
            'url': 'https://gitlab.com/api/v3/groups?per_page=500',
            'method': 'GET',
            'headers': {
                'private-token': GITLAB_API_PRIVATE_TOKEN,
                'cache-control': 'no-cache'
            }
        })
        .then((response) => { // and this
            console.log(response);
            this.groupsList = response.data; // and use the "this" variable here
        })
        .catch(function (error) {
            console.log(error);
        });
    }
}

Upvotes: 1

Related Questions