javascript - Adding elements to array in a for loop, empty array after loop -


so encountered following problem: have array keys used encrypt string. loop goes through array, encrypts string current key , pushes encrypted string new array. here code:

var enc_gmessages = ['start'];  for(i = 0; < 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             console.log(pgp_gmessage);             enc_gmessages.push(pgp_gmessage);         }).catch(function(error) {             console.log('error');         });     } } alert(enc_gmessages); 

while string gets encrypted (and logged in console) if there's valid public key, array contains 'start' element after loop. can please point out i'm doing wrong?

you're trying obtain value asynchronous operation before has completed.

that's not possible, should create new promise eventual result expected array of messages:

function getmessages(pubkeys) {      // array of promises each valid key - each element      // promise "resolved" 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);     });      // once resolved, return new promise     // resolved desired array     return promise.all(promises).then(function(messages) {         return ['start'].concat(messages);     }); } 

although .catch after promise.all line, more usual catch failures @ point invoked.

if "start" element in returned array there debugging , isn't required, replace entire return block return promise.all(promises).


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -