dthree / vorpal

Node's framework for interactive CLIs
http://vorpal.js.org
MIT License
5.63k stars 278 forks source link

Run script of my vorpal commands does not work on async functions #346

Open ghost opened 4 years ago

ghost commented 4 years ago

I tried to write a script runner, but it does not wait for async functions:

vorpal
    .command('run <file_name>', 'Run a script file')
    .validate(function (args) {
        if (fs.existsSync(args.file_name)) {
            return true;
        } else {
            return `File does not exists '${args.file_name}'`;
        }
    })
    .action(function (args, callback) {
        const scriptLines = fs.readFileSync(args.file_name).toString().split('\n');
        for (const line of scriptLines) {
            if (line.trim() !== '') {
                vorpal.execSync(line);
            }
        }
        callback();
    });

Tried that too, but it exits instantly:

vorpal
    .command('run <file_name>', 'Run a script file')
    .validate(function (args) {
        if (fs.existsSync(args.file_name)) {
            return true;
        } else {
            return `File does not exists '${args.file_name}'`;
        }
    })
    .action(async function (args, callback) {
        const scriptLines = fs.readFileSync(args.file_name).toString().split('\n');
        for (const line of scriptLines) {
            if (line.trim() !== '') {
                await vorpal.exec(line);
            }
        }
        callback();
    });

Any ideas?

ghost commented 4 years ago

Maybe before creating the Promise, there should be a test is it is async function.

function isAsync(func) {
    return func.constructor.name === "AsyncFunction";
}
lannierose commented 2 years ago

Late to the party here, but I solved this problem using sync-rpc to put my asynchronous operations into a worker thread. It's like magic! The main thread sees synchronous operation while the worker thread does the async stuff. Sounds complicated (for someone like me who never used workers before) but just follow the example in sync-rpc and it's not very difficult.