Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript promises and if/else statement

When I use filemanager function for directory (/) code works well, but when I call file (/index.html) code returns an error.

I see that the problem in if/else statement (readdir runs even if isDir returned false), but I don't know how correctly use it with promises.

var fs = require('fs'),
    Q = require('q'),
    readdir = Q.denodeify(fs.readdir),
    readFile = Q.denodeify(fs.readFile);

function isDir(path) {
    return Q.nfcall(fs.stat, __dirname + path)
        .then(function (stats) {
            if (stats.isDirectory()) {
                return true;
            } else {
                return false;
            }
        });
}

function filemanager(path) {
    if (isDir(path)) {
        return readdir(__dirname + path)
            .then(function (files) {
                return files.map(function (file) {
                    return ...;
                });
            })
            .then(Q.all);
    } else {
        return readFile(__dirname + path, 'utf-8')
            .then(function (content) {
                return ...;
            });
    }
}

filemanager('/').done(
    function (data) {
        ...
    },
    function (err) {
        ...
    }
);
like image 393
inetbug Avatar asked Feb 20 '14 14:02

inetbug


People also ask

What are the 3 states of a JavaScript promise?

A Promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation was completed successfully. rejected: meaning that the operation failed.

What are JavaScript promises?

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Why do we use if else statement in JavaScript?

Definition and Usage. The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.

How are promises executed in JavaScript?

The Promise constructor takes a function (an executor) that will be executed immediately and passes in two functions: resolve , which must be called when the Promise is resolved (passing a result), and reject , when it is rejected (passing an error).


2 Answers

isDir returns a promise, which is always a truthy value. You will need to put the condition in the then callback to have access to the boolean value:

function isDir(path) {
    return Q.nfcall(fs.stat, __dirname + path)
        .then(function (stats) {
            return stats.isDirectory()
        });
}

function filemanager(path) {
    return isDir(path).then(function(isDir) {
        if (isDir) {
            return readdir(__dirname + path)
                .then(function (files) {
                    return files.map(function (file) {
                        return ...;
                    });
                })
                .then(Q.all);
        } else {
            return readFile(__dirname + path, 'utf-8')
                .then(function (content) {
                    return ...;
                });
        }
    });
}
like image 78
Bergi Avatar answered Oct 02 '22 23:10

Bergi


Your call to isDir(path) evaluates to a Promise. So you cannot get the result directly from that function. Rather, you have to wait for that returned Promise to resolve, and then evaluate the value there. So, you need a construct like isDir(path).then(...) instead of the if (isDir(path)) that you are currently using.

like image 42
Brian H Avatar answered Oct 03 '22 01:10

Brian H