call callback once

This commit is contained in:
oleg 2014-12-04 23:22:14 +03:00
parent bdce719b4e
commit 26cb2aa9a1
2 changed files with 12 additions and 2 deletions

View File

@ -2,7 +2,8 @@
var spawn = require('child_process').spawn,
ParentCommand = require('./base').Command,
inherits = require('util').inherits;
inherits = require('util').inherits,
utils = require('../utils');
function Command(params) {
params = params || {};
@ -22,6 +23,7 @@ Command.prototype.run = function(params, callback) {
stdout = '';
if (!params.cmd) return callback(new Error('`cmd` is not set'));
if (!params.args) return callback(new Error('`args` is not set'));
callback = utils.once(callback);
params.options = params.options || {};
params.options.cwd = params.options.cwd || this.cwd;
var cmd = spawn(params.cmd, params.args, params.options);
@ -34,7 +36,6 @@ Command.prototype.run = function(params, callback) {
callback(new Error('Spawned command outputs to stderr: ' + data));
cmd.kill();
});
// TODO; callback should be called only once (port once from underscore)
cmd.on('close', function(code) {
var err = null;
if (code !== 0) err = new Error(

View File

@ -13,3 +13,12 @@ exports.isObject = function(obj) {
exports.noop = function() {};
exports.slice = Array.prototype.slice;
exports.once = function(func) {
var isCalled = false;
return function() {
if (isCalled) return;
func.apply(this, arguments);
isCalled = true;
};
};