我注意到MDN上的以下示例(最后一例),这使我相信有一种方法可以将SubtleCrypto函数的结果分配给变量。但据我所知/已经对异步/等待进行了研究,在async函数中只能使用async.
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/ most的结果赋值给没有.then()的变量。
对那些问自己为什么我会需要/想要这个的人来说。我正在使用WebCrypto和redux持久化相结合,但它似乎不能处理基于承诺的变换。
发布于 2017-03-21 22:32:37
该示例具有误导性(或不完整),您确实不能在async function之外使用async function。我刚刚编辑了它(MDN是一个wiki!)
是否可以将SubtleCrypto/ without的结果赋值给没有
.then()的变量。
是的,它将诺言对象存储在变量中。要访问承诺结果,您需要使用then或await。
https://stackoverflow.com/questions/42939339
复制相似问题