【问题标题】:Function works from command line but not within class函数从命令行工作,但不在类内
【发布时间】:2018-08-12 13:56:37
【问题描述】:

从命令行,这是有效的:

let blockchain = new Blockchain();
var bla;
blockchain.getBlockHeightPromise().then(i => bla =  i);

//bla 现在有了正确的值

从命令行,这不起作用:

let blockchain = new Blockchain();
blockchain.addBlock(someBlock)

//控制台日志表明bla未定义

更新:为什么从命令行运行的结果与从类中调用函数的结果不同?

//我的代码(略)

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

【问题讨论】:

  • getBlockHeightPromise 是异步的,所以在你的其余代码已经执行之后, bla 被设置为 i。查看相关问题:stackoverflow.com/questions/14220321/…
  • 对,那为什么这不起作用呢?我只在函数解析后设置 bla 。 this.getBlockHeightPromise().then(i => bla = i);也许在函数解析之前 console.log 正在触发?
  • 你在promise解决之后设置bla,是的,但是之后的console语句在promise解决之前执行。

标签: node.js scope bind blockchain leveldb


【解决方案1】:

控制台语句在来自getBlogHeightPromise 的承诺完成之前执行。

使用await等待异步方法getBlogHeightPromise解析:

    // Add new block
    async addBlock(newBlock) {
        var bla = await this.getBlockHeightPromise();
        console.log('bla: ' + bla);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-11
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 2013-08-19
    • 2013-06-28
    相关资源
    最近更新 更多