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

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

问题描述

当我对目录 (/) 使用 filemanager 函数时,代码运行良好,但是当我调用文件 (/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 语句中的问题(即使 isDir 返回 falsereaddir 也会运行),但我不知道如何正确地将它与 Promise 结合使用.

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 返回一个 promise,它总是一个真值.您需要将条件放在 then 回调中才能访问布尔值:

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天全站免登陆