I am learning bluebird and implementing in my code as below:
var getPromiseA = new Promise(function (resolve, reject) {
executeCommand('command A')
.then(function (result) {
var temp = JSON.parse(result);
for (var i in temp) {
if (temp[i].abc === 'ABC') {
resolve(temp[i]);
}
}
}).catch(function (err) {
console.log('Error occurred while executing getPromiseA :::');
reject(err);
});
});
var getPromiseB = new Promise(function (resolve, reject) {
executeCommand('command B')
.then(function (result) {
resolve(JSON.parse(result));
})
.catch(function (err) {
console.log('Error occurred while executing getPromiseB :::');
reject(err);
});
});
var getPromiseC = new Promise(function (resolve, reject) {
executeCommand('command C')
.then(function (result) {
var temp = JSON.parse(result);
for (var i in temp) {
console.log('in command C::::');
if (temp[i].abc != null) {
resolve(temp[i]);
}
}
})
.catch(function (err) {
console.log('Error occurred while executing getPromiseC :::');
reject(err);
});
});
function executeCommand(inputCmd) {
var commandPromise = new Promise(function (resolve, reject) {
var response = {}, err = {};
var command = exec(inputCmd);
command.stdout.on('data', function (data) {
response = data;
});
command.stderr.on('data', function (data) {
err = data;
});
command.on('close', function (code) {
console.log('coming in close' + code);
if (code === 0) {
console.log('before resolving in executeCommand');
resolve(response);
console.log('after resolving in executeCommand' + JSON.stringify(response));
}
else {
reject(code);
}
});
});
return commandPromise;
}
After this I am using Promise.all function to resolve all promises. I am facing the issue while resolving getPromiseC. PromiseC is not going into .then. I am not able to figure out what is the reason.
Output looks like below: For getPromiseA - 1.before resolving in executeCommand 2.after resolving in executeCommand - {data} 3.getPromiseA .then
For getPromiseB - 1.before resolving in executeCommand 2.after resolving in executeCommand - {data} 3.getPromiseB .then
For getPromiseC - 1.before resolving in executeCommand 2.after resolving in executeCommand - {data}
NOT printing 'getPromiseC .then' Control stucks here.But when try executing the function again,it resolves all the promises,i.e, I could see getPromiseC .then is printing in my console.
I am stuck since this issue happens intermittently.And the reload resolves the issue. When I call the function multiple times i see this resolving issue happens randomly.
Can someone help me to learn what is wrong this code?