在同步功能中使用javascript`crypto.subtle` [英] Using javascript `crypto.subtle` in synchronous function
问题描述
在javascript中,是否可以使用浏览器内置的sha256哈希( https://developer.mozilla.org/zh-CN/docs/Web/API/SubtleCrypto/digest#Converting_a_digest_to_a_hex_string )在同步函数中吗?
理想情况下,我想做类似的事情
String.prototype.sha256 = function() {
// ...
返回哈希值
}
我已经尝试过(async()=> {hash = await summaryMessage(message); return hash})()
之类的东西,但是我只能找回promise对象。
在我看来,可能无法实现我想要的目标,但我想我会在放弃之前先问一下。谢谢!
不,在您的 sync
函数中,您不能直接调用您的 Promise()
错误实施
const结果= utils.digestMessage(数据);
您必须使用 .then()。catch()
方法或 async / await
方法
正确实施
const utils = {};
utils.digestMessage =异步(数据)=> {
const hash = await crypto.digest(’SHA-256’,数据);
返回哈希值;
};
utils.digest =异步(数据)=> {
try {
const result = await utils.digestMessage(data);
的返回结果;
} catch(err){
throw err;
}
};
utils.digest(‘Neel’);
module.exports = utils;
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!
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;
这篇关于在同步功能中使用javascript`crypto.subtle`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!