[英]How to add addional logic before promise
I use the following code which works OK, now I need to add to it before the readFileAsync another method which query the Dir, my question is how to do that ? 我使用下面的代码可以正常工作,现在我需要在readFileAsync之前添加另一个查询Dir的方法,我的问题是怎么做?
this is currently the code which is working 这是当前正在工作的代码
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;
});
Now I need to add some process before which is like following: which should now return the path to the readfileAsync (the -relFilePath) How should I do that 现在,我需要添加一些类似于以下内容的过程:该过程现在应该将路径返回到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);
});
}
});
}); });
I use bluebird... 我用蓝鸟...
Just make a promise from it and chain it before the code that you already have… 只是从中做出承诺并在您已有的代码之前将其链接起来……
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.