首页 > 解决方案 > 如何完成generateHash函数?

问题描述

块.js

在 block.js 中,有一个generateHash函数。我无法使用 Promises 异步计算哈希并更新hash属性。

class Block {

        constructor(data){
            this.id = 0;
            this.nonce = 144444;
            this.body = data;
            this.hash = "";
        }

        generateHash() {
            // Use this to create a temporary reference of the class object
            let self = this;


            //Implement Promises here


        }
    }

    // Exporting the class Block to be reuse in other files
    module.exports.Block = Block;

应用程序.js

在 app.js 中,generateHash调用了函数并处理了 Promise,这对我来说很清楚:

const BlockClass = require('./block');

/**
 * Creating a block object
 */
const block = new BlockClass.Block("Test Block");

// Generating the block hash
block.generateHash().then((result) => {
    console.log(`Block Hash: ${result.hash}`);
    console.log(`Block: ${JSON.stringify(result)}`);
}).catch((error) => {console.log(error)});

标签: javascriptnode.jsblockchain

解决方案


您只需要编写返回已解决承诺的逻辑。

class Block {

  constructor(data) {
    this.id = 0;
    this.nonce = 144444;
    this.body = data;
    this.hash = "";

    this.generateHash = this.generateHash.bind(this);
  }

  generateHash() {
    return new Promise((resolve, reject) => {
      // Implement your hash logic here

      // simulate complex hash calculation
      setTimeout(() => {
        // returning random int(hex) for simplicity
        let hash = Math.floor(Math.random() * (2 << 21)).toString(16);
        this.hash = hash; // save new hash
        resolve(this); // resolve with this block
      }, 3000);
    });
  }
}

// Exporting the class Block to be reuse in other files
// module.exports.Block = Block;

/**
 * Creating a block object
 */
const block = new Block("Test Block");

getHash = async (testBlock) => {
  console.log(`Block[${testBlock.body}]: ${testBlock.hash}`);
  // Generating the block hash
  await testBlock.generateHash()
    .then(result => {
      console.log(`Block Hash: ${result.hash}`);
      console.log(`Block: ${JSON.stringify(result)}`);
    })
    .catch(console.log);
  console.log(`Block[${testBlock.body}]: ${testBlock.hash}`);
}

getHash(block);


推荐阅读