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,260 points
34 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,660 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
• 68,860 points
94 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 Aryya
• 7,340 points
56 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,090 points
226 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,810 points
205 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,660 points
116 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,660 points
168 views