gpt4 book ai didi

javascript - 异步/等待与 SubtleCrypto 结合使用

转载 作者:行者123 更新时间:2023-11-30 15:26:09 27 4
gpt4 key购买 nike

我注意到以下 example (last one)在 MDN 上,这让我相信有一种方法可以将 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');

示例不正确还是我误解了什么?最重要的是;是否可以在没有 .then() 的情况下将 SubtleCrypto/Promise 的结果分配给变量。

对于那些自问我到底为什么需要/想要这个的人。我正在与 redux-persist 结合使用 WebCrypto,但它似乎无法处理基于 Promise 的 transforms .

最佳答案

该示例具有误导性(或不完整),您确实不能在 async function 之外使用 await。我刚刚编辑了它(MDN 是一个 wiki!)。

Is it possible to assign the outcome of a SubtleCrypto/Promise to a variable without .then().

是的,它将 promise 对象存储在变量中。要访问 promise 结果,您需要使用 thenawait

关于javascript - 异步/等待与 SubtleCrypto 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939339/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com