Babra Cunningham Babra Cunningham - 14 days ago 6
Javascript Question

Manipulating values from outside Promise structures?

I'm using Promises to synchronize my hashing functions within my node application:

var example_int = '1000121';

function MakeRequest(value){
var hash_result = RequestHash(example_int);
hash_result.then(function(v){
//Do stuff with v...
})
}

function RequestHash(value){
return(Hash(value))
}

function Hash(value){
var HashPromise = new Promise(function(resolve, reject){
var crypto = require('crypto');
var hash = crypto.createHash('md5');

hash.on('readable', () => {
var data = hash.read();
if(data){
var output = data.toString('hex');
resolve(output);
}
})
hash.write(value);
hash.end();
})
return(HashPromise);
}

MakeRequest();


However, I want to be able to access the resulting hash values from outside the Promise functions. My initial approach was to use re-assignment:

var example_int = '1000121';

function MakeRequest(value){
var hash_result = RequestHash(example_int);
//Hash output assigned to example_int....
}

function RequestHash(value){
return(Hash(value))
}

function Hash(value){
var HashPromise = new Promise(function(resolve, reject){
var crypto = require('crypto');
var hash = crypto.createHash('md5');

hash.on('readable', () => {
var data = hash.read();
if(data){
var output = data.toString('hex');
example_int = output; //Re-assignment...
resolve(output);
}
})
hash.write(value);
hash.end();
})
return(HashPromise);
}

MakeRequest();


Is there a safer way and/or more efficient method of performing this without the reliance on re-assingment?

Answer

The hash API is not asynchronous in node.js, so there is no need for promises to begin with.

Code as simple as this:

var crypto = require('crypto');

var exampleValue = '1000121';
var md5Val = crypto.createHash('md5').update(exampleValue).digest('hex');
// -> '4f0b7e8fcb0cfcfce1c77e39864e7ca4'

does the job just fine. If you want, wrap it in a function.

If your real issue involves an asynchronous part then you need to ask the question with more details.