【问题标题】:Async/await in combination with SubtleCrypto异步/等待与 SubtleCrypto 结合
【发布时间】: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


    【解决方案1】:

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

    是否可以将 SubtleCrypto/Promise 的结果分配给没有.then() 的变量。

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

    【讨论】:

    • 好吧,我以为我快疯了...感谢您的澄清。看来我得深入研究 redux-persist 了。
    猜你喜欢
    • 2020-04-12
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2014-02-21
    • 1970-01-01
    • 2019-06-13
    相关资源
    最近更新 更多