En un curso en línea para desarrolladores de cadenas de bloques en el que participo, un requisito previo era la programación asíncrona y orientada a objetos de JavaScript, en la que no tengo experiencia. Sin embargo, al tener algo de experiencia en programación, pensé que aprendería sobre la marcha.
Una actividad de práctica (no calificada, en las que no puedo obtener ayuda) sobre hash de blockchain quiere que creemos una función de hash asíncrono usando promesas de hash de datos con SHA256. Hay 2 archivos principales: app.js y block.js.
app.js (nos lo dieron, es el archivo principal que ejecutamos):
/** * Importing the Block class */ // const BlockClass = require('./block.js'); /** * 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)}); /** * Step 3: Run the application in node.js * */ // From the terminal: cd into Project folder // From the terminal: Run node app.js to run the codeblock.js (las flechas indican la parte que agregué yo mismo, se proporcionó todo lo demás.
/** * 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 = ""; } /** * 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() { // Use this to create a temporary reference of the class object let self = this; > //Implement your code here > self.hash = SHA256(JSON.stringify(self.body)); > const promise = new Promise(function(myResolve,myReject){ > if(self.hash = SHA256(JSON.stringify(self.body))){ > myResolve(self); > }else{ > myReject(Error("It Broke")); > } > > }); > > promise.then( > function(result){this.hash = result.hash;}, > function(error){console.log(error);} > ); > } } // Exporting the class Block to be reuse in other files module.exports.Block = Block;Utilizando recursos en línea, entiendo las promesas, pero no realmente, y definitivamente no cómo aplicarlas aquí. Esperaba poder obtener ayuda con esto.