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

node js async function return Promise { <pending> }

我曾尝试测试一个加密的东西,我是 nodejs 的新手。

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

案例:调用异步方法来加密数据,但是 return 我用 Promise { <pending> }

即时通讯使用 npm openpgp

objective: return 密文所以我可以将它用于其他目的

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

请帮忙

Async Await 只是语法糖,用于承诺异步函数 returns 承诺。

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

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

// using promises

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

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

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

我试图访问这个东西而不必声明 'async' 词并且可以访问 'res' 所以我可以用于其他目的

非常感谢。