Async function returning before result

0

I have this function in JS, using Forge library, for key pair generation. The problem is 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 send printar, I see that it sends Null, and then printa in the console

    
asked by anonymous 12.11.2018 / 16:58

2 answers

1

You do not need async / await for the scenario you want. The problem is in using the wrong overload for what you need, the 'rsa.generateKeyPair' function.

You can use the same rsa.generateKeyPair function without having 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);
    
12.11.2018 / 18:12
1

You can try to use async / await in 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;   
};
    
12.11.2018 / 17:04