-1

I am using nodejs with this library node-jose, to get allow me to do get my private key and using it to sign and/or decript.

So the problem now is this. I am trying to return a signature from result after generating it by is unable to do so.

At Point A, when I do a console.log, i am to actually see my result. Beyond that, i.e. at Point B, i am unable to see my result. All i get is this.

2018-10-23T15:04:23.553 signature1: null //Point B

Am i doing things the right way?


main.js:

let jose = require('node-jose');

function sendRequest(id, keystore, kid1, kid2) {
    let result;

    ... 

    let baseString1 = generateBaseString(baseUrl1);
    let signature1 = null;
    jose.JWS.createSign(keystore.get(kid1)).update(baseString1).final().then(function(result) {

        signature1 = result;
        //Point A
        console.log(result);
    });

    //Point B
    console.log("signature1: " + signature1);

    ...

    return result;
}
shadow
  • 800
  • 2
  • 16
  • 33
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Oct 23 '18 at 07:08
  • @CertainPerformance i don't think is the same. The returning call from jose.JWS.createSign(key) is a promise. – shadow Oct 23 '18 at 07:11
  • It's asynchronous, so you can't use `let signature1 = generateSignature(...`. You have to call `.then` on Promises to get to the value they resolve to. – CertainPerformance Oct 23 '18 at 07:15
  • @CertainPerformance I edited the question to simplify things. Is it still wrong to do it this way? – shadow Oct 23 '18 at 08:01

1 Answers1

0

try to use the async/await features

async function sendRequest(id, keystore, kid1, kid2) {
    let result;

    ... 

    let baseString1 = generateBaseString(baseUrl1);
    let signature1 = await jose.JWS.createSign(keystore.get(kid1)).update(baseString1).final();

    //Point B
    console.log("signature1: " + signature1);

    ...

    return result;
}

Your point A doesn't mean it will be executed first than your point B the .then() in promise only executed if the operation/promise is already resolve.

Maybe this will help you to understand Promise https://codeburst.io/javascript-promises-explained-with-simple-real-life-analogies-dd6908092138