javascript - 如何从此 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
解决方案
推荐阅读
- sql - 在时态表和 AVERAGE 中成功查询后返回非重复值
- jquery - 在另一个函数中使用来自一个函数的变量
- c# - 即使在实现 INotifyPropertyChanged 之后,DataTemplate 中的字典也不会更新 UI
- ios - SwiftUI:如何在背景中模糊的当前视图顶部弹出一个视图?
- python-3.x - 服务总线未在 Azure 上触发,在本地工作
- angular - Angular Material 反应形式:为每个验证器显示不同的错误消息
- css - 为什么我的媒体查询范围不能正常工作?
- vuejs2 - 带有 flex/grid 包装器的 vue 过渡组项目移动到左上角
- android - HTML 原生应用无法在大尺寸手机上正确适配横向模式。不能强行合身
- node.js - JWT 身份验证授权不起作用