vinayr vinayr - 10 months ago 62
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();