Search code examples
node.jsscopebindblockchainleveldb

Function works from command line but not within class


From the command line, this works:

let blockchain = new Blockchain();
var bla;
blockchain.getBlockHeightPromise().then(i => bla =  i);

//bla now has the correct value

From the command line, this doesn't work:

let blockchain = new Blockchain();
blockchain.addBlock(someBlock)

//Console log indicates that bla is undefined

Update: Why do results differ running from command line vs. calling the function from within the class?

//My code (abbreviated)

    class Blockchain {
    constructor() {
    }


    // Add new block
    async addBlock(newBlock) {
        var bla;
        this.getBlockHeightPromise().then(i => bla = i);
        console.log('bla: ' + bla);}
//Note addBlock needs to async because await db.createReadStream follows


    getBlockHeightPromise() {
        return new Promise(function (resolve, reject) {
            let i = 0;

            db.createReadStream()
                .on('data', function () {
                    i++;
                })
                .on('error', function () {
                    reject("Could not retrieve chain length");
                })
                .on('close', function () {
                    resolve(i);
                });
        })
    }
}

Solution

  • The console statement is executed before the promise from getBlogHeightPromise is finished.

    Use await to wait for the asynchronous method getBlogHeightPromise to resolve:

        // Add new block
        async addBlock(newBlock) {
            var bla = await this.getBlockHeightPromise();
            console.log('bla: ' + bla);
        }