C
C
chelnokov_a2021-07-09 11:55:19
JavaScript
chelnokov_a, 2021-07-09 11:55:19

How to use a class property in a method if it is returned asynchronously?

Hello. There was a problem.

My class has a property which is obtained asynchronously.
And there is a method that uses this property.
This method is called immediately after the instantiation of the class when the page is loaded.

class Favorite = {
    constructor(opt) {
        this.state = // получаем в результате промиса
    }

    nyMethod () {
         console.log(this.state)
    }
}


It looks like this.

As you understand, I get undefined in the console. Tell me what I'm missing. More precisely, I understand what the problem is, but I don’t know how to correctly approach its solution) Thank you

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
chelnokov_a, 2021-07-09
@chelnokov_a

Understood.
You need to abandon the this.state property and get the state in a separate method that will return the promise. For example like this

class Favorite = {
    constructor(opt) {
    }
    getState () {
        return state = // // получаем в результате промиса
    }
    nyMethod () {
        getState().then(state => {
            console.log(state)
        })
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question