Verspricht mit fs und Bluebird

Ich lerne gerade, wie man Versprechen in nodejs verwendet

Daher bestand meine erste Herausforderung darin, Dateien in einem Verzeichnis aufzulisten und dann den Inhalt beider Schritte mithilfe von asynchronen Funktionen abzurufen. Ich habe die folgende Lösung gefunden, habe aber das starke Gefühl, dass dies nicht der eleganteste Weg ist, dies zu tun, insbesondere im ersten Teil, in dem ich die asynchronen Methoden in Versprechen "verwandle"

// purpose is to get the contents of all files in a directory
// using the asynchronous methods fs.readdir() and fs.readFile()
// and chaining them via Promises using the bluebird promise library [1]
// [1] https://github.com/petkaantonov/bluebird 

var Promise = require("bluebird");
var fs = require("fs");
var directory = "templates"

// turn fs.readdir() into a Promise
var getFiles = function(name) {
    var promise = Promise.pending();

    fs.readdir(directory, function(err, list) {
        promise.fulfill(list)
    })

    return promise.promise;
}

// turn fs.readFile() into a Promise
var getContents = function(filename) {
    var promise = Promise.pending();

    fs.readFile(directory + "/" + filename, "utf8", function(err, content) {
        promise.fulfill(content)
    })

    return promise.promise
}

Verketten Sie nun beide Versprechen:

getFiles()    // returns Promise for directory listing 
.then(function(list) {
    console.log("We got " + list)
    console.log("Now reading those files\n")

    // took me a while until i figured this out:
    var listOfPromises = list.map(getContents)
    return Promise.all(listOfPromises)

})
.then(function(content) {
    console.log("so this is what we got: ", content)
})

Wie ich oben geschrieben habe, gibt es das gewünschte Ergebnis zurück, aber ich bin mir ziemlich sicher, dass es einen eleganteren Weg gibt.

Antworten auf die Frage(1)

Ihre Antwort auf die Frage