首页 > 解决方案 > 如何从此 javascript 承诺中正确返回值

问题描述

我有一个名为 block.js 的类,它应该有一个名为 generatorHash() 的方法,该方法应在为其分配一个新属性即其“哈希”后返回“块”

我们需要将块分配给 this 关键字,然后在 promise 得到解决后,我们应该将新返回的哈希值分配给 'self(block).hash'

这是代码:

/**
 * Import crypto-js/SHA256 library
 */
const SHA256 = require("crypto-js/sha256");

/**
 * Class with a constructor for block
 */
class Block {
  constructor(data) {
    this.id = 0;
    this.nonce = 144444;
    this.body = data;
    this.hash = this.self.hash;
  }

  /**
   * Step 1. Implement `generateHash()`
   * method that return the `self` block with the hash.
   *
   * Create a Promise that resolve with `self` after you create
   * the hash of the object and assigned to the hash property `self.hash = ...`
   */
  //
  generateHash() {
    let self = this;
    return new Promise((resolve, reject) => {
      // Implement your hash logic here
      this.self.hash = console.log(SHA256(JSON.stringify(self)).toString());
      resolve(self);
    });
  }
}
// Exporting the class Block to be reuse in other files
module.exports.Block = Block;

错误是:

this.hash = this.self.hash;
                                ^

TypeError: Cannot read property 'hash' of undefined
    at new Block (/home/workspace/Project/block.js:15:30)
    at Object.<anonymous> (/home/workspace/Project/app.js:10:15)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

标签: javascriptpromisethis

解决方案


推荐阅读