【问题标题】:How to return resolving Promise Like object from for loop如何从 for 循环返回解析 Promise Like 对象
【发布时间】:2019-03-09 06:09:42
【问题描述】:

我在自己的函数中有一个类似对象的承诺,它使用网络加密 API 解密给定的消息。问题是,在我的解密函数中,我想尝试几个不同的值作为输入,并在 for 循环中多次运行这个类似对象的承诺,最后函数应该返回这些承诺成功解决的对象。

public decryptMessage(latitude: [string, number], longitude: [string, number], ciphertext: string) {
    //get salt 
    const salt = localStorage.getItem("salt")
    const retrievedSaltArray = JSON.parse(salt)
    const saltBytes = new Uint8Array(retrievedSaltArray)

    //get iv
    const iv = localStorage.getItem("iv")
    const retrievedIvArray = JSON.parse(iv)
    const ivBytes = new Uint8Array(retrievedIvArray)

    //get tolerance distance
    let toleranceDistance = parseInt(JSON.parse(localStorage.getItem("toleranceDistance")))

    //get original keyHash
    let originalHash = localStorage.getItem("keyhash")

    //create location inputs(locations with adjacent quadrants)
    let location = new Location(latitude, longitude)
    let locationInputs = location.prepareReceiverLocationInputs()

    let encryptionTool = new EncryptionHelper(saltBytes, ivBytes)

    for (let i = 0; i <= locationInputs.length - 1; i++) {
        let plaintText = encryptionTool.decrypt(locationInputs[i], ciphertext, originalHash)
        plaintText.then(function (plaintTextResult) {
            return plaintTextResult
        })
    }

}

所以我在这里尝试做的是,这个 promise Like ojbect 是 encryptionTool.decryp() 应该在 for 循环中运行,然后这些 promise 中的任何一个解析应该是 decryptMessage 方法的返回值。但是,此 encryptionTool.decrypt 方法使用 webcrypto api,因此它没有拒绝或捕获方法,因为它是类似 promise 的方法。

【问题讨论】:

    标签: javascript typescript promise


    【解决方案1】:

    由于 Promise 表示将来可用的值,因此您无法“现在”(同步)测试哪个成功。相反,您必须使用可用的函数来操作和组合 Promise。我假设encryptionTool.decrypt 返回一个PromiseLike&lt;string&gt;;如果它是 PromiseLike&lt;T&gt; 用于其他 T,只需在下面将 string 替换为 T。

    首先,您可以使用Promise.resolve 将PromiseLike&lt;string&gt; 转换为Promise&lt;string&gt;。然后,您想使用Promise.all 获取一个promise 数组并将结果数组的promise 返回给您,因此您可以编写一个then 回调来扫描数组并获取您想要的结果。一个潜在的问题是Promise.all 拒绝如果 any 所提供的承诺拒绝,在这种情况下您看不到其他结果。所以在使用Promise.all之前,需要使用catch将拒绝映射到一个标记值,比如null。完整的代码应该是这样的(我没有测试过,所以可能会有错误):

        // Assuming that encryptionTool.decrypt returns a PromiseLike<string>,
        // promises will be a Promise<string | null>[].
        let promises = [];
        for (let i = 0; i <= locationInputs.length - 1; i++) {
            promises.push(
                Promise.resolve(encryptionTool.decrypt(locationInputs[i], ciphertext, originalHash))
                .catch((error) => null));
        }
        return Promise.all(promises).then((results) => {
            // results is a (string | null)[].
            // Look through it, find the non-null result and return it.
        });
    

    请注意,最终的then 调用会为最终结果生成一个promise,并且您将此promise 同步返回给decryptMessage 的调用者。

    另一种方法是将decryptMessage 设为异步函数,以便您可以以更熟悉的风格进行编程。将public decryptMessage 替换为public async decryptMessage,然后使用如下代码:

        for (let i = 0; i <= locationInputs.length - 1; i++) {
            try {
                return await encryptionTool.decrypt(locationInputs[i], ciphertext, originalHash);
            } catch (e) {
                // Discard the exception and proceed to the next decryption attempt.
            }
        }
        // TODO: Decide what to return here if all decryptions fail.
    

    请注意,这样一来,每次解密都会在前一次解密失败后开始,因此该过程可能需要更长的时间才能完成,具体取决于网络加密 API 的实现方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2019-03-25
      • 1970-01-01
      相关资源
      最近更新 更多