Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

node.js - 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) {
        ...
    }
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ...;
                });
        }
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...