JavaScript承诺和if / else语句 [英] JavaScript promises and if/else statement

查看:122
本文介绍了JavaScript承诺和if / else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我对目录( / )使用 filemanager 函数时,代码效果很好,但是当我调用file( /index.html )代码返回错误。

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

我在if / else语句中看到问题( readdir 即使 isDir 返回 false 也会运行,但我不知道知道如何正确地将它与promises一起使用。

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


推荐答案

isDir 返回一个承诺,它总是一个真正的价值。您需要将条件放在然后回调中才能访问布尔值:

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

这篇关于JavaScript承诺和if / else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆