vinayr vinayr - 2 months ago 12
Node.js Question

if-else flow in promise (bluebird)

This is a short version of my code.

var Promise = require('bluebird');
var fs = Promise.promisifyAll(require("fs"));

if (conditionA) {
fs.writeFileAsync(file, jsonData).then(function() {
return functionA();
});
} else {
functionA();
}


Both conditions call
functionA
. Is there way to avoid else condition? I can do
fs.writeFileSync
but I am looking for a non-blocking solution.

Answer

I think you're looking for

(conditionA 
  ? fs.writeFileAsync(file, jsonData)
  : Promise.resolve())
.then(functionA);

which is short for

var waitFor;
if (conditionA)
    waitFor = fs.writeFileAsync(file, jsonData);
else
    waitFor = Promise.resolve(undefined); // wait for nothing,
                                          // create fulfilled promise
waitFor.then(function() {
    return functionA();
});