0

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);
                });
        })
    }
}
Mark Maslar
  • 1,121
  • 4
  • 16
  • 28
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Patrick Hund Aug 12 '18 at 14:07
  • `getBlockHeightPromise` is aynchronous, so bla is set to i after the rest of your code has already been executed. See related question: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Patrick Hund Aug 12 '18 at 14:07
  • Right, so why doesn't this work? I'm only setting bla after the function resolves. this.getBlockHeightPromise().then(i => bla = i); Perhaps console.log is firing before the function resolves? – Mark Maslar Aug 12 '18 at 14:15
  • You're setting bla after the promise resolves, yes, but the console statement after that is executed before the promise resolves. – Patrick Hund Aug 12 '18 at 14:17

1 Answers1

0

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);
    }
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95