我在MDN上注意到了下面的例子(最后一个(,这让我相信有一种方法可以将SubtleCrypto函数的结果分配给变量。但据我所知/已经研究了异步/等待,只能在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');
这个例子是不正确的还是我误解了什么?最重要的是;是否可以在没有.then()
的情况下将 SubtleCrypto/Promise 的结果分配给变量。
对于那些问自己为什么我需要/想要这个的人。我正在将WebCrypto与redux-persist结合使用,但它似乎不能处理基于Promise的转换。
该示例具有误导性(或不完整(,您确实不能在async function
之外使用await
。我刚刚编辑了它(MDN是一个维基!
是否可以在没有
.then()
的情况下将SubtleCrypto/Promise的结果分配给变量。
是的,这会将 promise 对象存储在变量中。要访问承诺结果,您需要使用 then
或 await
。