节点js异步函数返回Promise {<pending>}

时间:2019-01-18 03:21:59

标签: javascript node.js promise openpgp

我曾经尝试过测试加密的东西,并且是Nodejs的新手。

经过几次尝试并搜索了google,我无法解决我的问题。 请帮忙。

案例:调用异步方法来加密数据,但是它返回一个Promise { <pending> }

我使用npm openpgp

目标:返回密文,以便我将其用于其他目的

我的代码如下: //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
            }
};

请帮助

2 个答案:

答案 0 :(得分:3)

异步等待只是用于承诺的语法糖异步函数返回承诺。

您不能在顶层使用await。您可以做的是:

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

// using promises

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

答案 1 :(得分:-1)

tools.encrypt().then(res => console.log(res))

来自@mark meyer的这一行解决了我的问题。

我试图访问事物而不必声明“异步”字并可以访问“ res”,以便我可以将其用于其他目的

非常感谢。

相关问题