javascript - 如何在 Promise 之前添加额外的逻辑

标签 javascript node.js promise bluebird

我使用以下代码可以正常工作,现在我需要在 readFileAsync 之前添加另一个查询目录的方法,我的问题是如何做到这一点?

这是当前正在运行的代码

    var filePath = path.join(__dirname, '../userpath');

    return fs.readFileAsync(filePath, 'utf8')
        .then(pars.getEx.bind(null, 'user'))
        .then(process.bind(null, 'exec'))
        .then(function (result) {
            return result.stdout;
        }, function (error) {
            return error;
        });

现在我需要添加一些流程,如下所示: 现在应该返回 readfileAsync 的路径(-relFilePath) 我该怎么做

var filePath = path.join(__dirname, '../../../../employess');

fs.readdir(filePath, function (err, files) {
    files.forEach(function (file) {
        if (file.indexOf('emp1') === 0) {

            // this should be returned 
            var relFilePath = filePath + '/' + file + '/unpath.txt';

            console.log(relFilePath);
            fs.readFile(relFilePath,'utf8', function read(err, data) {
                if (err) {
                    throw err;
                }
                console.log(data);
            });
        }
    });

});

我用 Bluebird ...

最佳答案

只需从中做出 promise 并将其链接在您已有的代码之前......

var filePath = path.join(__dirname, '../../../../employess');
fs.readdirAsync(filePath)
.then(function(files) {
    for (var i=0; i<files.length; i++)
        if (file.indexOf('emp1') === 0)
            return filePath + '/' + file + '/unpath.txt';
    throw new Error("no file with emp1 found");
})
.then(function(relFilePath) {
    return fs.readFileAsync(relFilePath, 'utf8');
})
.then(pars.getEx.bind(null, 'user'))
.then(process.bind(null, 'exec'))
.then(function (result) {
    return result.stdout;
}).then(function(data) {
    console.log(data);
}, function (error) {
    console.error(error.message);
});

关于javascript - 如何在 Promise 之前添加额外的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31914147/

相关文章:

javascript - 在 Node 中使用 Promise 在函数之间传递数据

node.js - 在项目数组上使用 Sequelize 创建/更新

javascript - 自 2019 年 8 月 28 日起,Edge 中的 Facebook connect javascript SDK 问题

javascript - 如何四舍五入到小数点后两位?

javascript - 如何在 mongodb 中使用 $nin 运算符从集合中获取文档

node.js - Node.js 的非阻塞 ClientRequest.write()

javascript - Angularjs 中 $location 上的 Url 重定向问题 - 无法读取未定义的属性 'path'

javascript - 平滑图像淡出,更改 src,并使用 jquery 淡入

node.js - Angular '/' 路线不适用于 Express

angular - 尝试在 Angular 中缓存 HttpClient 请求,但看到未解析的变量