小编Hen*_*rik的帖子

与fs和蓝鸟的承诺

我目前正在学习如何在nodejs中使用promises

所以我的第一个挑战是列出目录中的文件,然后使用异步函数获取每个步骤的内容.我提出了以下解决方案,但有一种强烈的感觉,这不是最优雅的方式来做到这一点,尤其是我将异步方法"转变"为承诺的第一部分

// 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 …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous fs node.js bluebird

19
推荐指数
1
解决办法
1万
查看次数

标签 统计

asynchronous ×1

bluebird ×1

fs ×1

javascript ×1

node.js ×1