如何处理与JavaScript Promise相关的情况?

时间:2018-12-02 13:02:23

标签: javascript node.js es6-promise

我有以下JavaScript脚本。我正在尝试为区块链的工作方式构建示例脚本。我将所有块数据存储在级别DB中。

const SHA256 = require('crypto-js/sha256');
var levelDB = require('./levelSandbox');

class Block{
    constructor(data){
    this.hash = "",
    this.height = 0,
    this.body = data,
    this.time = 0,
    this.previousBlockHash = ""
    }
}

class Blockchain{

    constructor(levelDB){
        this.levelDB = levelDB;
        this.blocksInLevelDB = {};
        this.chain = {};

        this.getBlockHeight()
            .then(height => {
                if(!height){
                    this.addBlock(new Block("First block in the chain - Genesis block"));
                }
            })        
    }

    // Method for adding new block
    addBlock(newBlock){
        this.getBlockHeight()
            .then(height => {
                console.log('block height is: ', height);
                console.log('blocksInLevelDB: ', this.blocksInLevelDB);

                // Set block hight
                newBlock.height = height;

                // Set UTC timestamp
                newBlock.time = new Date().getTime().toString().slice(0,-3);

                // Set previous block hash
                if(height > 0){
                    let blockData = JSON.parse(this.blocksInLevelDB[height-1]);
                    newBlock.previousBlockHash = blockData.hash;
                }

                // Block hash with SHA256 using newBlock and converting to a string
                newBlock.hash = SHA256(JSON.stringify(newBlock)).toString();

                console.log('newBlock obj: ',newBlock);

                // Adding block object to chain & save in level db
                this.levelDB.addLevelDBData(height, JSON.stringify(newBlock))
                    .then(console.log('Block added to level db'))
                    .catch(function(err){console.log('Error in adding new block: ', err)})


            })
    }

    // Get block height
    getBlockHeight(){
        return this.levelDB.getAllDataFromLevelDB()      
            .then(data => {
                let blockHeight = data.length;
                for (const elem of data){
                    this.blocksInLevelDB[elem.key] = elem.value;
                }
                return blockHeight;
            })
            .catch(function(err){
                return err;
            });
    }
}

在正常情况下,一切正常,除了--p

情况1- 当级别DB没有数据(空)时,如果我运行以下代码,则只有一条记录插入到级别DB中,而不是两条。

var blockChain = new Blockchain(levelDB);
blockChain.addBlock(new Block('Second block in the chain'));

但是,如果我像这样修改上面的代码-

var blockChain = new Blockchain(levelDB);
setTimeout(function(){ 
    blockChain.addBlock(new Block('Second block in the chain'));
}, 3000);

然后工作正常(插入两个记录)。

情况2- 如果Level DB有多个记录,并且如果我尝试再添加一个记录,则可以正常工作。例如。

var blockChain = new Blockchain(levelDB);
blockChain.addBlock(new Block('Third block in the chain'));

但是,当我尝试添加多个记录时,只有一个记录被插入(最后一个)。例如。

var blockChain = new Blockchain(levelDB);
blockChain.addBlock(new Block('Third block in the chain'));
blockChain.addBlock(new Block('Fourth block in the chain'));
blockChain.addBlock(new Block('Fifth block in the chain'));

我知道这是由于promise(异步性质)而发生的,在该情况下,我对getBlockHeight()的所有调用均异步执行并获得相同数量的记录(区块链高度)。因此,在添加新的块时,所有记录都使用相同的键插入并相互覆盖。但是,无法理解解决这种情况的正确方法。

1 个答案:

答案 0 :(得分:1)

好的,这是大概的执行顺序:

let a = [ 'E', 'v', 'a', 'n', ' ', 'C', 'o', 'l', 'e' ]
a.filter((val, i) => {
  return val.length === 1 && val.match(/[A-Z]/);
})

为避免这种情况,您可能还应该对BlockChain类使用异步模式。

类似的东西:

new Blockchain(levelDB);
this.levelDB = levelDB;      // constructor
this.blocksInLevelDB = {};   // constructor
this.chain = {};             // constructor
this.getBlockHeight()        // ASYNC, constructor
|    blockChain.addBlock(new Block('Second block in the chain'));
|    this.getBlockHeight()   // ASYNC, called by ^
|    |
L----+--- if (!height)       // true
     |    this.addBlock(new Block("First blo..
     |    this.getBlockHeight()                              // ASYNC
     |    |
     L--- +---> ... this.levelDB.addLevelDBData(height, ...) // ASYNC
          |         // ^ second block is added, at height 0
          |
          L---> ... this.levelDB.addLevelDBData(height, ...)
                    // ^ first block is added, again at height 0

为此,您将需要定义一个let blockChain = new BlockChain(levelDB); blockChain.init() .then(() => blockChain.addBlock( new Block('Second block in the chain'))) .catch(...); 方法来检查高度,插入第一个块并返回一个init()