I use the following code which works OK,Currenlty the pars.getEx is returning a string to run to the processExe method,Now I need somehow to pass also port from other function to processExe ,how can I do that ?
var portscanner = require('portscanner');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require("fs"));
.....
return fs.readFileAsync(filePath, 'utf8')
.then(pars.getEx.bind(null, 'user'))
.then(processExe.bind(null, 'exec'))
.then(function (result) {
return result.stdout;
}, function (error) {
return error;
});
The processExe looks like following
function processExe(method, cmd) {
return new Promise(function (resolve, reject) {
var child = child_process[method](cmd, function (error, stdout, stderr) {
The port can be achieved with the following OS
https://github.com/baalexander/node-portscanner
portscanner.findAPortNotInUse(3000, 4000, 'localhost', function (error,
port) {
UPDATE
to the processExe I should provide the port like following
the port should come from the findPort
var options = {
PORT: port,
};
and here i also pass options
var child = child_process[method](cmd,options, function (error, stdout,
If you want/need a parameter, just add a parameter:
function processExe(method, cmd, port) {
return new Promise(function (resolve, reject) {
var child = child_process[method](cmd, {
PORT: port,
}, function (error, stdout, stderr) {
…
});
…
});
}
As always, the asynchronous function should return a promise, how many parameters it has (one, two, or now three) doesn't matter. You should not try to find some special way to pass the values that are needed because the function will be used under certain circumstances, that's a separate concern and should not influence the design of your function.
Now, how to pass additional parameters when the function is invoked within a promise chain? Well, you seem to know that already, function expressions and .bind
are at your service. The problem is rather that the source of your argument values is not a single promise, but rather two asynchronous processes - the one that reads and parses a file and the one that finds a port. Since both are async, we expect them both to return promises; you should be able to promisify portscanner
just like you did fs
.
When you have two or more promises, you can combine them using Promise.all
:
return Promise.all([
fs.readFileAsync(filePath, 'utf8').then(pars.getEx.bind(null, 'user')),
portscanner.findAPortNotInUseAsync(3000, 4000, 'localhost')
]).then(function(args) {
return processExe('exec', args[0], args[1]);
})
We can simplify this a bit though by using Promise.join
:
return Promise.join(
fs.readFileAsync(filePath, 'utf8').then(pars.getEx.bind(null, 'user')),
portscanner.findAPortNotInUseAsync(3000, 4000, 'localhost'),
processExe.bind(null, 'exec')
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.