[英]How do I get access to my outer variable from a predefined callback I pass in?
[英]How do I get access to a variable without nested callback?
我有一个使用Node FileSystem模块的简单嵌套回调,并且在尝试访问仅由于作用域链而变得可用的变量时遇到了困难。 我的目标是尽可能减少嵌套的回调。
var fs = require('fs');
var directory = '/Users/johndoe/desktop/temp';
fs.readdir(directory, function(err, files) {
files.forEach(function(file) {
var filePath = directory + "/" + file;
fs.readFile(filePath, function(err, data) {
// I have access to filePath variable here. This works just fine.
console.log(filePath);
});
});
});
但这是我想写的:
var fs = require('fs');
var directory = '/Users/johndoe/desktop/temp';
fs.readdir(directory, processFiles);
function processFiles(err, files) {
files.forEach(function(file) {
var filePath = directory + "/" + file;
fs.readFile(filePath, processSingleFile);
});
}
function processSingleFile(err, data) {
// how do I get the filePath variable here?
console.log(filePath);
}
在第二个示例中,如何在此处获取filePath变量?
您可以通过绑定将filePath
作为第一个参数传递给processSingleFile
。
function processFiles(err, files) {
files.forEach(function(file) {
var filePath = directory + "/" + file;
fs.readFile(filePath, processSingleFile.bind(this, filePath));
});
}
function processSingleFile(filePath, err, data) {
console.log(filePath);
}
将processSingleFile
更改为function returning function
,并将变量filePath
作为变量传递给该function returning function
。 像波纹管
function processSingleFile(filePath) {
return function(err, data){
console.log(filePath);
console.log(data);
}
}
叫它像波纹管
fs.readFile(filePath, processSingleFile(filePath));
var fs = require('fs');
var directory = '/Users/johndoe/desktop/temp';
fs.readdir(directory, processFiles);
// declaring filePath outside to allow scope access
var filePath;
function processFiles(err, files) {
files.forEach(function(file) {
filePath = directory + "/" + file;
fs.readFile(filePath, processSingleFile);
});
}
function processSingleFile(err, data) {
// You can access filePath here
console.log(filePath);
}
function processFiles(err, files) {
files.forEach(function(file) {
var filePath = directory + "/" + file;
fs.readFile(filePath, function(err,data){
processSingleFile(data,filePath);
});
});
}
function processSingleFile(data, filePath) {
// You can access filePath here
console.log(filePath);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.