0

i had try to test out an encryption stuff and im new to nodejs.

after several try and search over google, i unable to solve my problem. please help.

case: calling async method to encrypt data, however it return me with a Promise { <pending> }

im using npm openpgp

objective: return the ciphertext so i could use it for other purpose

my code as below: //execution.js

var tools = require('./tools');
console.log(tools.encrypt());

//tools.js

const openpgp = require('openpgp') // use as CommonJS, AMD, ES6 module or via window.openpgp
var fs = require('fs');
openpgp.initWorker({ path:'openpgp.worker.js' }) // set the relative web worker path

var pubkey = fs.readFileSync('public.key', 'utf8');
const passphrase = `super long and hard to guess secret` //what the privKey is encrypted with

module.exports = {
    encrypt:async () =>{
        const options = {
                message: openpgp.message.fromText('Hello, World!'),       // input as Message object
                publicKeys: (await openpgp.key.readArmored(pubkey)).keys, // for encryption
            }

            const encrypted = await openpgp.encrypt(options);
            const ciphertext = encrypted.data;

            fs.writeFile('message.txt',ciphertext ,'utf8', function (err) {
              if (err) throw err;
              console.log('msg written!');
            });

            return ciphertext;
    },
    decrypt: async function(){
                // your code here
            }
};

please help

3
  • 2
    So whats the problem? await it? Commented Jan 18, 2019 at 3:23
  • async functions return promises. You need to anticipate that and use something like tools.encrypt().then(res => console.log(res)) Commented Jan 18, 2019 at 3:26
  • 1
    thanks a lot @MarkMeyer . i think i could use your solution Commented Jan 18, 2019 at 3:53

2 Answers 2

3

Async Await is simply syntactic sugar for promises an async function returns a promise.

You can't use await at the top level. What you can do is:

(async () => {
    try {
        console.log(await tools.encrypt());
    } catch (e) {
        console.log(e);
    }
})();

// using promises

tools.encrypt().then(console.log).catch(console.log);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks bro. both ur answer and @mark meyer give me a clear view over this problem.
-1
tools.encrypt().then(res => console.log(res))

this line from @mark meyer solve my problem.

i was trying to access the thing without have to declare the 'async' word and have access to the 'res' so i could use for other purpose

Thanks alot.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.