问题
In javascript, is it possible to use the browser built-in sha256 hash (https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#Converting_a_digest_to_a_hex_string) inside a synchronous function?
Ideally, I'd like to do something like
String.prototype.sha256 = function() {
// ...
return hash
}
I already tried things like (async() => {hash = await digestMessage(message); return hash})()
, but I can only get back the promise object.
It seems to me that it might not be possible to achieve what I want, but I thought I'll ask here before giving up. Thanks!
回答1:
No, In your sync
function you can't directly call your Promise()
Wrong Implement
const result = utils.digestMessage(data);
You must need to use .then().catch()
approach or async/await
approach
Right Implement
const utils = {};
utils.digestMessage = async (data) => {
const hash = await crypto.digest('SHA-256', data);
return hash;
};
utils.digest = async (data) => {
try {
const result = await utils.digestMessage(data);
return result;
} catch (err) {
throw err;
}
};
utils.digest('Neel');
module.exports = utils;
回答2:
What about waiting for the response and use ".then((res)=>{})" after finish. res would contain your desired information
promise.then((response) =>{
const hah = response.data;//I'm not sure about property data. might be different
}
来源:https://stackoverflow.com/questions/57626477/using-javascript-crypto-subtle-in-synchronous-function