kbpgp icon indicating copy to clipboard operation
kbpgp copied to clipboard

using await for easy async programming

Open j3g opened this issue 5 years ago • 2 comments

I'm a little frustrated. I read that the project choose coffee script, and created iced coffee script for "two additions (await and defer) that make async programming much nicer". So I've been really confused and frustrated that all the example code in javascript is a callback. Also the coffeescript is anonymous callbacks also. We all want easy to read async code. I have tried so many different tricks but it seems that since the library is missing promises I cannot have clean code with using the await. The API has a simple, elegant design. Not too complicated.

Can the library only use callbacks? Is everyone using this library writing in coffeescript? Any actual documentation other than the few examples? For example, classes, members, properties.

j3g avatar Nov 13 '20 20:11 j3g

I cannot wait on the generate() which is really annoying

async function pgp_test() {
  let opts = getOpts();
  let keyMgr;
  console.log("1111");
  await kbpgp.KeyManager.generate(opts, (err, mgr) => {
    console.log("2222");
    if (mgr)
      keyMgr = mgr;
  });
  console.log("3333");
  console.log(keyMgr);
}

Output is:

1111
3333
undefined
2222

The await works on other functions:

console.log("1111");
let pubkey;
await keyMgr.export_pgp_public({}, (err, key) => {
  console.log("2222");
  if (key)
    pubkey = key;
});
console.log("3333");
console.log("pubkey: ", pubkey);

Output is:

1111
2222
3333
pubkey:  -----BEGIN PGP PUBLIC KEY BLOCK-----

j3g avatar Nov 13 '20 21:11 j3g

I did more research. Here is how we can bring modern code to this thang.

const util  = require('util');

// no callbacks!!!
async function genKey(opts) {
  try {
    let retKey;
    let keyGen = util.promisify(kbpgp.KeyManager.generate);
    console.log("[INFO] key generation in process...");
    retKey = await keyGen(opts);
    console.log("[INFO] completed");
    return retKey;
  }
  catch(ex) {
    console.error(ex);
  }
}

async function genAndExport() {
  try {
    // generate 2 keys, sequently, waiting for each one, no callbacks!!
    let opts = {};
    opts['userid'] = "User A (Born 1976) <[email protected]>";
    mUserA = await genKey(opts);
    opts['userid'] = "User B (Born 1976) <[email protected]>";
    mUserB = await genKey(opts);
  }
  catch(ex) {
    console.error(ex);
  }
}

j3g avatar Nov 16 '20 05:11 j3g