代码之家  ›  专栏  ›  技术社区  ›  Alex Dovzhanyn

执行继续,不承诺解决

  •  0
  • Alex Dovzhanyn  · 技术社区  · 7 年前

    我正在使用节点库 level 从LevelDB实例中读取所有数据。我正在包装 水平 带有一个承诺的库,以便我可以将结果设置为变量。出于某种原因,承诺永远不会兑现,而且 this.chain 只是一个未解决的承诺。

    const Ledger = require('./ledger')
    
    class Blockchain {
      constructor() {
        this.ledger = new Ledger()
        this.chain = this.ledger.getAllBlocks()
        console.log(this.chain) // logs Promise { <pending> }
      }
    }
    
    module.exports = Blockchain
    

    const leveldb = require('level')
    
    class Ledger {
      constructor() {
        // This will create or open the underlying LevelDB store.
        this.db = leveldb('./.ledger.dat')
      }
    
    getAllBlocks() {
        return new Promise((res, rej) => {
          let stream = this.db.createReadStream()
          let blocks = []
    
          stream.on('data', data => {
            blocks.push(data.value)
          })
          .on('end', () => res(blocks))
        })
        .then(blocks => blocks)
      }
    }
    
    module.exports = Ledger
    

    编辑 根据Benitos请求,以下是im如何初始化blockback.js:

    const Blockchain = require('./src/blockchain')
    
    let itpChain = new Blockchain(5.0)
    
    while(true) {
      itpChain.run()
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Benito    7 年前

    console.log(this.chain)

    this.chain.then(result => console.log(result))

    Blockchain 是吗?我想试试这个:

    // Blockchain.js
    const Ledger = require('./ledger')
    
    class Blockchain {
      constructor() {
        this.ledger = new Ledger()
        this.chain = this.ledger.getAllBlocks()
      }
      getBlocks()
        return this.chain
      }
    }
    
    module.exports = Blockchain
    

    // app.js
    const Blockchain = require('./Blockchain')
    const bc = new Blockchain()
    bc.getBlocks().then(results => console.log(results))
    
        2
  •  1
  •   Jordan Soltman    7 年前

    在您的代码中,this.chain是一个未解决的承诺。我们需要等待这个值。

    this.ledger = new Ledger()
    this.ledger.getAllBlocks().then(result => {
      console.log(result); // this will have the value
    });
    
    推荐文章