Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
Why are JS class instance properties null after setting?

This is a nodejs / express MVC app. I've got a custom model called MyModel (not really, but for privacy, let's pretend that's the name). The properties of the class are set as null by default:

export class MyModel {

    /* ----- FIELDS ----- */
    protected _id: string = null;
    protected _name: string = null;
    ...

The constructor only sets the name property, all other properties are set by database triggers. So in my save method (which persists to the db), it works kind of like this:

    async save() {
        let client:PoolClient = null;
        try {
            client = await pool.connect();
            let query;
            if (this._id === null) {
                query = {
                    name: 'insertMyModel',
                    text: 'INSERT INTO my_model (name) VALUES ($1::text) RETURNING id',
                    values: [this._name],
                    rowMode: 'array',
                };

            } else {
                ...
            }

            const result = await client.query(query);
            if (this._id === null) {
                this._id = result.rows[0][0];
                ...

The controller, simply (for now) returns MyModel to string, which should show the returned id.

    public async new(req, res) {
        try {
            const mymodel = await MyModel.new(req.params.name);

            res.send(mymodel.toString());
        } catch (error) {
            res.status(400).send(error);
        }
    }

And (thank you @Barmar for noticing) I forgot to include MyModel's new function, so adding that here. This constructs the new MyModel instance and then calls save.

    public static async new(name: string) : Promise<GekModel> {
        if (name === undefined || name === null || (name = name.trim()) === '') {
            name = uniqueNamesGenerator();
        }

        const mymodel = new MyModel(name);
        mymodel.save();
        return mymodel;
    }

Using interactive debugging, I've determined that in the save method, indeed, the db is propertly returning the ID. And I've seen that in the save method, the returned id is assigned to the _id property. However, by the time I get back to the controller's new, the _id property is back to null. boink.

I assume this has something to do with the async nature of it? But, I'm at a loss. Would love any ideas!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Big thanks @Barmar for the suggestion of writing a minimal code reproducible version of this problem. I was able to whittle it down to 24 lines and realized that the problem was in the mymodel.save() line. I was calling save synchronously, when it's an async method. Therefore the toString() method was getting called before the id was set. I added an "await" before that and it's working now.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda