Home > OS >  js promise wait until resolved to continue "main"
js promise wait until resolved to continue "main"

Time:11-25

How can I force a function to resolve a pending promise before using it in JavaScript

  generateKey(pass, iter).then(function(result) {
    Pkey = result;
  });

above Pkey returns <empty string> before resolving i could write a loop to check for non-emptiness but that seems counterintuitive, no?

and

  Pkey = generateKey(pass, iter);

returns a pending promise that is eventually fulfilled

function generateKey(passwd, iterations) {

  var encoder = new TextEncoder('utf-8');
  var passphraseKey = encoder.encode(passwd);
  var saltBuffer = encoder.encode("carthage");

  return crypto.subtle.importKey(
    'raw',
    passphraseKey,
    {name: 'PBKDF2'},
    false,
    ['deriveBits', 'deriveKey']
  ).then(function(key) {
//    console.log(key);
    return window.crypto.subtle.deriveKey(
    { "name": 'PBKDF2',
      "salt": saltBuffer,
      "iterations": iterations,
      "hash": 'SHA-256'
    },
    key,
    { "name": 'AES-CBC',
      "length": 256
    },
    true,
    [ "encrypt", "decrypt" ]
  )
  }).then(function (webKey) {
//    console.log(webKey);
    return crypto.subtle.exportKey("raw", webKey);
  }).then(function (buffer) {
//    console.log(buffer);
//    console.log(saltBuffer);
//    console.log("Private Key = "   buf2hex(buffer));
//    console.log("Salt = "   bytesToHexString(saltBuffer));
    return buffer;
  });

}



function buf2hex(buffer) { // buffer is an ArrayBuffer
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00'   x.toString(16)).slice(-2)).join('');
}



function bytesToHexString(byteArray) {
  return Array.prototype.map.call(byteArray, function(byte) {
    return ('0'   (byte & 0xFF).toString(16)).slice(-2);
  }).join('');
}

CodePudding user response:

You can use async & await as below

async function generateKey(passwd, iterations) {...}
...
Pkey = await generateKey(pass, iter);
  • Related