0

I am using child-process-promise module. So I have something like this:

var promise = require('child-process-promise').spawn;

promise('some_command_producing_output')
    .then(function (result) {
        ...
    })
    .catch(function (err) {
        ...
    });

What I want is to add some processing after command produced output in stdout. So finally I want to create a function to use like this:

RunCommandAndProcess('some_command_producing_output')
    .then(function (result) {
        ...
    })
    .catch(function (err) {
        ...
    });

The function should use promise from child-process-promise, wait until successful result produced and return promise for processing data.

Pablo
  • 28,133
  • 34
  • 125
  • 215
  • So, `function RunCommandAndProcess(x) { return spawn(x) }`? There's noting magic about promises, they're just values that you can pass around and return from your helper function. – Bergi Feb 28 '18 at 09:19
  • The processing function, which I need to perform after spawning should be done asynchronously, using promise. – Pablo Feb 28 '18 at 09:23
  • So insert `.then(process)`? – Bergi Feb 28 '18 at 09:24
  • assuming `process` is returning promise, but I would like to combine them into single promise. – Pablo Feb 28 '18 at 09:25
  • Yes, `process` can return a promise. [`then` works just like that](https://stackoverflow.com/a/22562045/1048572). – Bergi Feb 28 '18 at 09:27

1 Answers1

0

It's really just

var spawn = require('child-process-promise').spawn;
function RunCommandAndProcess(cmd) {
    return spawn(cmd).then(function process(result) {
        … // do processing
        return …;
    });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • So in processing routine I have to create and return another promise, in order to make `RunCommandAndProcess` thenable, right? I would like to have `RunCommandAndProcess.then(...)`. – Pablo Feb 28 '18 at 09:41
  • You can return or throw anything. The `then()` call always returns a promise that resolves with whatever result your callback has. – Bergi Feb 28 '18 at 10:00