Async function returning before result

Asked

Viewed 55 times

0

I have this function in JS, using Forge library, for generating pair of keys. The problem that when trying to use the async function to perform the generation, the function is returning before generating the result.

function generateKeys(keySize, storageName) {
    var rsa = forge.pki.rsa;
    // var keys = forge.pki.rsa.generateKeyPair(keySize);
    var p1 = rsa.generateKeyPair({bits: keySize, workers: -1}, function(err, keypair) {
        var privateKey = keypair.privateKey;
        var publicKey = keypair.publicKey;
        sessionStorage.setItem(storageName, JSON.stringify(privateKey));

        var csr = forge.pki.createCertificationRequest();
        csr.publicKey = publicKey;
        csr.sign(privateKey);

        // convert certification request to PEM-format
        var certReqPem = forge.pki.certificationRequestToPem(csr);
        console.log(certReqPem);
        return certReqPem;
    });    
};

I get this return in my HTML to forward to a PHP form, however, it is coming NULL, but if I print it, I see that it sends Null, and then print it on the console

2 answers

1

You can try using async/await the following way

function async generateKeys(keySize, storageName) {
    var rsa = forge.pki.rsa;
    // var keys = forge.pki.rsa.generateKeyPair(keySize);
    var keypair = await rsa.generateKeyPair({bits: keySize, workers: -1});
    var privateKey = keypair.privateKey;
    var publicKey = keypair.publicKey;
    sessionStorage.setItem(storageName, JSON.stringify(privateKey));

    var csr = forge.pki.createCertificationRequest();
    csr.publicKey = publicKey;
    csr.sign(privateKey);

    // convert certification request to PEM-format
    var certReqPem = forge.pki.certificationRequestToPem(csr);
    console.log(certReqPem);
    return certReqPem;   
};
  • In HTML it looks like this: var publicKeyPem = generateKeys(keySize, "privateKeyPem"); When I do console.log on this variable, a promise in the pending state is coming.

  • That’s why when being a prop, you have to run with async/await to make the execution of the promise awaiting its end async functions

  • Um, you say utilize . then? I’m trying, but without much success

  • No, VC can do con I state in response, with async and await

  • I did as it is there, it is returning a promise, as said in the first reply

  • In the first answer you don’t do var publicKeyPem = await generateKeys(keySize, "privateKeyPem");

  • await da este erro: Syntaxerror: await is only Valid in async functions and async generators, que é bem estranho, pois a função está declarado como async

  • Take the function to help

  • 1

    Ah got it, the problem I was calling it in another function in HTML, ai put async in it too, and await as said earlier, it worked, thanks.

Show 4 more comments

1


No async/await is required for the scenario you want. The problem is using the incorrect overload for what it needs, the 'rsa.generateKeyPair' function'.

You can use the same function rsa.generateKeyFor no need to pass a callback and it’s all solved.

Below I send the code and with a test just below (just copy and paste):

function generateKeys(keySize, storageName) {

    var rsa = forge.pki.rsa;
    // var keys = forge.pki.rsa.generateKeyPair(keySize);
    var keypair = rsa.generateKeyPair({bits: keySize, workers: -1});    

    var privateKey = keypair.privateKey;
    var publicKey = keypair.publicKey;
    ssessionStorage.setItem(storageName, JSON.stringify(privateKey));

    var csr = forge.pki.createCertificationRequest();
    csr.publicKey = publicKey;
    csr.sign(privateKey);

    // convert certification request to PEM-format
    var certReqPem = forge.pki.certificationRequestToPem(csr);

    return certReqPem;    
};

Testing:

const x = generateKeys(...);

console.log(x);
  • It really works, my question is this: I need performance, which approach is more correct? It seems that async is faster

  • So Vinicius, this is very relative and it also depends on whether the library you are using has the asynchronous feature or you would need to wrap to return a Promise. You gain performance with asynchronous features when it makes sense for you to put tasks to run in parallel. But in your case, you need to wait for the key to return to continue your program, so there is no need for parallel tasks. I recommend reading this article if you wish: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/funcoes_asynchrons

  • I think my answer is correct and the one you marked as correct is wrong, because the 'await' recommended in the friend’s reply is irrelevant and was not necessary, even though the function was async. Take 'await' and buy, because the function 'generateKeyPair' does not return a Promise to need 'await'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.