【问题标题】:Adding elements to array in a for loop, empty array after loop在for循环中向数组添加元素,循环后为空数组
【发布时间】:2016-01-07 16:16:16
【问题描述】:

所以我遇到了以下问题:我有一个带有用于加密字符串的密钥的数组。 for 循环遍历数组,使用当前密钥加密字符串,然后将加密的字符串推送到新数组中。代码如下:

var enc_gmessages = ['start'];

for(i = 0; i < pubkeys.length; i++) {
    var pubkey = pubkeys[i];

    if(pubkey != 'no' && pubkey != null) {
        var publicKey = openpgp.key.readArmored(pubkey);
        openpgp.encryptMessage(publicKey.keys, content).then(function(pgp_gmessage) {
            //string encrypted successfully
            console.log(pgp_gmessage);
            enc_gmessages.push(pgp_gmessage);
        }).catch(function(error) {
            console.log('error');
        });
    }
}
alert(enc_gmessages);

如果存在有效的公钥,则字符串会成功加密(并登录到控制台),但数组仅包含 for 循环后的“开始”元素。有人可以指出我做错了什么吗?

【问题讨论】:

  • 加密例程是异步的。该代码使用网络工作者(不确定它在 Node 中的作用)。因此,for 循环在加密之前完成。
  • 你需要把它封装在一个返回Promise的函数中。
  • 如果你移动警报会发生什么(enc_gmessages);到您的 enc_gmessages.push(pgp_gmessage); 之后的行。 ?
  • @Tokn 那里已经有一个console.log() 呼叫。
  • @Pointy 我看不到

标签: javascript loops for-loop


【解决方案1】:

您正试图在异步操作完成之前从它获取一个值。

这是不可能的,所以你应该做的是创建一个新的 Promise,其最终结果将是预期的消息数组:

function getMessages(pubkeys) {

    // get an array of Promises for each valid key - each element is 
    // a promise that will be "resolved" with the encrypted message
    var promises = pubkeys.filter(function(pubkey) {
        return pubkey != null && pubkey != 'no';
    }).map(function(pubkey) {
        var publicKey = openpgp.key.readArmored(pubkey);
        return openpgp.encryptMessage(publicKey.keys, content);
    });

    // then once all are resolved, return a new promise that
    // is resolved with the desired array
    return Promise.all(promises).then(function(messages) {
        return ['start'].concat(messages);
    });
}

虽然您可以在Promise.all 行之后.catch,但更常见的是在调用它时捕获任何故障。

如果返回数组中的“开始”元素仅用于调试,实际上并不需要,只需将整个返回块替换为return Promise.all(promises)

【讨论】:

    【解决方案2】:

    我认为承诺系统在这里造成了麻烦。 在 openpgp.encryptMessage(...) 返回的每个 promise 的回调中将元素推送到数组中,因此循环在任何操作实际发生之前结束。

    【讨论】:

    • 鉴于 OP 已经在使用 Promise,这不是等待它们全部完成的方式。这就是Promise.all() 的用途。
    • 这段代码有同样的问题——encryptionCompleted() 函数并没有真正做任何事情;返回的函数被忽略。
    猜你喜欢
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2018-01-27
    • 1970-01-01
    • 2019-04-02
    • 2019-11-05
    • 1970-01-01
    相关资源
    最近更新 更多