我使用以下代码可以正常工作,现在我需要在 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/