Ad
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);
});
})
}
}
Ad
Answer
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);
}
Ad
source: stackoverflow.com
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error
Ad