Using javascript `crypto.subtle` in synchronous function

喜欢而已 提交于 2020-05-15 06:48:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!