【发布时间】:2017-03-22 06:32:37
【问题描述】:
我注意到 MDN 上的以下 example (last one) 让我相信有一种方法可以将 SubtleCrypto 函数的结果分配给变量。但据我所知/已经研究过 async/await 只能在 async 函数中使用 await...
async function sha256(message) {
const msgBuffer = new TextEncoder('utf-8').encode(message); // encode as UTF-8
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer); // hash the message
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert ArrayBuffer to Array
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join(''); // convert bytes to hex string
return hashHex;
}
sha256('abc').then(hash => console.log(hash));
const hash = await sha256('abc');
示例不正确还是我误解了某些内容?最重要的是;是否可以将 SubtleCrypto/Promise 的结果分配给没有.then() 的变量。
对于那些问自己为什么我需要/想要这个的人。我正在将 WebCrypto 与 redux-persist 结合使用,但它似乎无法处理基于 Promise 的 transforms。
【问题讨论】:
标签: javascript promise async-await redux