Function not working from class

0 votes

I have this class:

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);

                });

        })

    }

}


Now when I try to run it, it doesn’t work:

let blockchain = new Blockchain();

blockchain.addBlock(someBlock)

But it works from the command line when I try to run it like this:

let blockchain = new Blockchain();

var bla;

blockchain.getBlockHeightPromise().then(i => bla =  i);

How to make this work?

Aug 16, 2018 in Blockchain by slayer
• 29,170 points
30 views

1 answer to this question.

0 votes

Try this code: 


// Add new block

    async addBlock(newBlock) {

        var bla = await this.getBlockHeightPromise();

        console.log('bla: ' + bla);

    }

The function is not working when you call it within the class is because the console statement is executed before getBlogHeightPromise is finished.

Using await to wait for the asynchronous method getBlogHeightPromise solves this problem

answered Aug 16, 2018 by digger
• 26,550 points

Related Questions In Blockchain

0 votes
1 answer

Geth 'sendTransaction' not working

When transactions are put in a loop, ...READ MORE

answered Jul 3, 2018 in Blockchain by Omkar
• 67,660 points
69 views
0 votes
1 answer

Is it possible to claim Bitcoin Cash from an exchange that does not support it?

You can't claim BCH without knowing private ...READ MORE

answered Jul 17, 2018 in Blockchain by ariaholic
• 7,340 points
47 views
+1 vote
2 answers
0 votes
1 answer

My first Hyperledger fabric network is not working

Delete as admin the channel-artifacts folder, down ...READ MORE

answered Aug 10, 2018 in Blockchain by Johnathon
• 9,080 points
159 views
0 votes
1 answer

Truffle tests not running after truffle init

This was a bug. They've fixed it. ...READ MORE

answered Sep 11, 2018 in Blockchain by Christine
• 15,790 points
169 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

OpenSSL i2o_ECPublicKey not working

When your right something in the buffer, ...READ MORE

answered Aug 17, 2018 in Blockchain by digger
• 26,550 points
91 views
0 votes
1 answer

Not receiving any data from the BitStamp API.

I saw a code online that was ...READ MORE

answered Aug 21, 2018 in Blockchain by digger
• 26,550 points
89 views