执行仍然没有承诺解决

时间:2018-06-16 22:08:24

标签: javascript node.js promise

我正在使用节点库level来读取leveldb实例中的所有数据。我正在使用promise包装level库的readStream,以便我可以将结果设置为变量。出于某种原因,承诺永远不会解决,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的要求,这是我如何初始化Blockchain.js:

const Blockchain = require('./src/blockchain')

let itpChain = new Blockchain(5.0)

while(true) {
  itpChain.run()
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

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