0

I have a class with a constructor function and a hash function to hash certain variables. I used promises to set the variable. Here is my code:

import * as bcrypt from 'bcrypt'
import {Promise} from 'es6-promise';
const saltR: Number = 10;

export default class Hi{
    test: String;

    constructor(test: String){
        this.hash(test)
            .then((hash: String) => {
                console.log(hash)
                this.test= hash
                console.log(this.test)
            })
            .catch(err => console.error(err));
            console.log(`seller: ${this.test}`)
    }

    private hash(toBeHashed: String){
        return new Promise((resolve, reject) => {
            bcrypt.genSalt(saltR, (err, salt) => {
                if(err) reject(err);

                bcrypt.hash(toBeHashed, salt, (err, hash: String) => {
                    if(err) reject(err);

                    resolve(hash);
                });
            });
        });
    }
}

When I console.log the variable this.test after my catch() it says undefined. How can I actually set this variable and have it last?

Olivier Depriester
  • 1,615
  • 1
  • 7
  • 20
  • As @GuyIncognito says the Promise is async and when your reach ```console.log(`seller: ${this.test}`)```, your variable is not yet set. But actually you are already reading the content of your ```this.test``` value in the ```then()``` callback (just below the ```this.test = hash``` and that's exactly the right place to do it – Olivier Depriester Apr 26 '20 at 16:49
  • Make the constructor return the promise and use it with `await`. See [this](https://stackoverflow.com/a/50885340/941240) as a reference. But never expect the value to be initialized **before** the promise is resolved. – Wiktor Zychla Apr 26 '20 at 18:47

0 Answers0