javascript - 如何完成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)});
解决方案
您只需要编写返回已解决承诺的逻辑。
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);
推荐阅读
- amazon-rds - 我应该为符合 HIPAA 和 PCI-DSS 的数据使用单独的数据库吗?
- wso2 - 如何从修复传输 wso2 的响应中获取值
- sql - 第三高使用的编程语言 PostgreSQL
- angular - 如何以角度在一个垫表数据源中显示 2 个数组列表?
- android - 当 shouldsimulate 为 false 时,mapbox android 导航崩溃
- jenkins - 来自并行作业的 Jenkins 工件
- mysql - 如何在 Node.js 的 UPDATE 中正确使用 WHERE?
- java - if-else 和 if 仅当方法具有 return 语句时-它们是否相同?
- angular - 物体变化的角度变化检测
- node.js - 带有nodejs的附件SendinBlue Api