Q promises - Node.js函数用于数组中的每个元素 [英] Q promises - Node.js function for every element in the array

查看:112
本文介绍了Q promises - Node.js函数用于数组中的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数 dirList()应返回definded目录中的文件夹数组。我无法理解如何在为每个文件执行函数 isDir()之后返回 dirList 变量。

Function dirList() should return array of folders inside definded directory. I can't understand how return dirList variable only after the function isDir() is executed for each file.

我想我应该使用 Q.all(),但我不知道应该把它放在哪里: - (

I guess that I should use Q.all(), but I don't know where I should put it :-(

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

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

function dirList(path) {
    return readdir(__dirname + path).then(function (files) {
        var dirList = files.filter(function (file) {
                return isDir(path + file).then(function (isDir) {
                    return isDir;
                });
            });
        return dirList;
    });
}

dirList('/').done(
    function (data) {
        console.log(data);
    },
    function (err) {
        console.log(err);
    }
);


推荐答案

您遇到的问题是 Array.prototype.filter 不知道promises,所以它只看到一个truthy值(实际上是一个promise对象)并将文件添加到输出列表中。解决问题的一种方法如下(AsyncJS可能采用更清洁的方式):

The problem you're experiencing is that Array.prototype.filter doesn't know about promises, so it just sees a truthy value (actually a promise object) and adds the file to the output list. One way to solve the problem follows (there may be a "cleaner" way possible with something like AsyncJS):

'use strict';

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

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

function dirList(path) {
    return readdir(__dirname + path).then(function (files) {
        // here we map the list of files to an array or promises for determining
        // if they are directories
        var dirPromises = files.map(function (file) {
            return isDir(path + file);
        });
        // here is the Q.all you need
        return Q.all(dirPromises)
            // here we translate the array or directory true/false values back to file names
            .then(function(isDir) {
                return files.filter(function(file, index) { return isDir[index]; });
            });
    });
}

dirList('/').done(
    function (data) {
        console.log(data);
    },
    function (err) {
        console.log(err);
    });

这篇关于Q promises - Node.js函数用于数组中的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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