简体   繁体   中英

Using promises with Node.js functions on example

I'm started learning JavaScript promises, but I can't understand how apply, for example, Q functions to Node.js callback functions.

In similar question is recommended to use Q.denodeify() , but it works well for fs.readFile() and don't works for fs.exists() .

This is a simple functions that returns list of files and their sizes in directory:

function openDir(path, callback) {
    path = __dirname + path;
    fs.exists(path, function (exists) {
        if (exists) {
            fs.readdir(path, function (err, files) {
                if (err) {
                    throw err;
                }
                var filesCounter = 0,
                    filesTotal = files.length,
                    result = [];
                files.forEach(function (filename, index) {
                    fs.stat(path + filename, function (err, stats) {
                        if (err) {
                            throw err;
                        }
                        result[index] = {};
                        result[index].name = filename;
                        result[index].size = stats.size;
                        if (++filesCounter === filesTotal) {
                            callback(result);
                        }
                    });
                });
            });
        }
    });
}

http.createServer(function (req, res) {
    openDir('/', function (data) {
        res.writeHead(200, {
            'Content-Type': 'application/json; charset=utf-8'
        });
        res.end(JSON.stringify(data));
    });
}).listen(1337, '127.0.0.1');

How write this code using promises (with Q or other library)?

fs.exists is kind of a useless method. It does not return a node style call back and can usually be omitted. In your example you would handle the error from fs.readdir .

fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code. node docs

Here is your example reworked with Q, note that we defer error handling to the caller by returning a promise instead of the stats themselves. I included an example of how to handle fs.exists with Q.defer to show how you can proxy non node style callbacks.

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

function stat(file){
    return Q.nfcall(fs.stat, file)
        .then(function(stats){
            stats.filename = file;
            return stats;
        });
}

function openDir(path) {
    path = __dirname + path;

    return readdir(path)
        .then(function(files) { 
            return files.map(function(file){ 
                return stat(path + file); }); })
        .then(Q.all);
};

// proxy fs.exists to return a promise. Example of Q.defer
function exists(file){
    var deferred = Q.defer();
    fs.exists(file, function(result){
        return result ? deferred.resolve(file) : deferred.reject('invalid file');    
    });
    return deferred.promise;
}

http.createServer(function (req, res) {
    openDir('/').done(
        function (data) {
            res.writeHead(200, {
                'Content-Type': 'application/json; charset=utf-8'});
            res.end(JSON.stringify(data));
        },
        function (err) {
            res.writeHead(500, {
                'Content-Type': 'application/json; charset=utf-8'});
            res.end(JSON.stringify({error: err}));
        });
    }).listen(1337, '127.0.0.1');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM