vinayr vinayr - 1 year ago 95
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 {

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

Answer Source

I think you're looking for

  ? fs.writeFileAsync(file, jsonData)
  : Promise.resolve())

which is short for

var waitFor;
if (conditionA)
    waitFor = fs.writeFileAsync(file, jsonData);
    waitFor = Promise.resolve(undefined); // wait for nothing,
                                          // create fulfilled promise
waitFor.then(function() {
    return functionA();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download