函数在命令行中有效,但在 class 中无效
Function works from command line but not within class
从命令行,这有效:
let blockchain = new Blockchain();
var bla;
blockchain.getBlockHeightPromise().then(i => bla = i);
//bla 现在有了正确的值
从命令行,这不起作用:
let blockchain = new Blockchain();
blockchain.addBlock(someBlock)
//控制台日志提示bla未定义
更新:为什么命令行的结果与从 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);
});
})
}
}
控制台语句在 getBlogHeightPromise
的承诺完成之前执行。
使用await
等待异步方法getBlogHeightPromise
解析:
// Add new block
async addBlock(newBlock) {
var bla = await this.getBlockHeightPromise();
console.log('bla: ' + bla);
}
从命令行,这有效:
let blockchain = new Blockchain();
var bla;
blockchain.getBlockHeightPromise().then(i => bla = i);
//bla 现在有了正确的值
从命令行,这不起作用:
let blockchain = new Blockchain();
blockchain.addBlock(someBlock)
//控制台日志提示bla未定义
更新:为什么命令行的结果与从 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);
});
})
}
}
控制台语句在 getBlogHeightPromise
的承诺完成之前执行。
使用await
等待异步方法getBlogHeightPromise
解析:
// Add new block
async addBlock(newBlock) {
var bla = await this.getBlockHeightPromise();
console.log('bla: ' + bla);
}