jondot / hygen

The simple, fast, and scalable code generator that lives in your project.
http://www.hygen.io
MIT License
5.68k stars 256 forks source link

Add async helpers #99

Open jondot opened 5 years ago

jondot commented 5 years ago

Context: https://github.com/jondot/hygen/issues/95

csdswarm commented 4 years ago

It looks like ejs should have async support if you add async: true to the render options. What that looks like I'm not quite clear.

In any case, I'm already finding times when I would like to be able to utilized helpers that get data from sources that may be asynchronous in nature, so this would be a great feature to have.

csdswarm commented 4 years ago

Okay, in case anyone else is looking for this, I found an excellent workaround that already exists in hygen depending on what you need to do.

Create a generator and add an index.js to it.

expose a params method as an async function and wait for the results.

looks something like this:

const { promisify } = require('util');
const exec = promisify(require('child_process').exec);

module.exports = {
  params: async () => {
    const { stdout } = await exec('git rev-parse --abbrev-ref HEAD');
    const branch = (`${stdout}`).trim().toUpperCase();

    return {  branch };
  }
};

Then just use <%= branch %> in your template.

rameshjanjyam commented 3 years ago

@csdswarm thank you. it worked. I couldn't get this and interactive prompting both work in same generator. Have you tried it? if so did u get it to work?

csdswarm commented 3 years ago

@rameshjanjyam TBH, I've moved on to a different scaffolding tool. I'm currently using plop mostly because that uses handlebars syntax, which is already a syntax being used in the project I'm on. Even then, I've had a hard time getting around to building scaffolds in it.

EDIT: You may want to see if spawn works better than exec. spawn doesn't generate a separate shell to work from. spawn does require a bit of different syntax.

rameshjanjyam commented 3 years ago

Thank you @csdswarm