This question already has an answer here:
这个问题在这里已有答案:
- How do I return the response from an asynchronous call? 32 answers
- 如何从异步调用返回响应? 32个答案
- Get data from fs.readFile 10 answers
- 从fs.readFile获得数据10个答案
I'm trying to return arr when final() is called....
我试图在调用final()时返回arr ....
function final(){
var arr;
fs.readFile("/my/path/", 'utf8' ,(err, data) => {
arr = parsing(data);
arr.splice(-1,1);
});
return arr;
}
It keeps returning undefined. Even though arr inside the readFile brackets gives me an array...
它不断返回undefined。即使readFile括号内的arr给我一个数组......
The possible duplicate discusses printing whereas I need a value to use somewhere else. How can I use the value arr in another function/module?
可能的重复讨论打印,而我需要一个值来使用其他地方。如何在另一个函数/模块中使用值arr?
2 个解决方案
#1
0
readFile
is async function you need to do this
readFile是你需要执行此操作的异步函数
function final(){
var arr;
fs.readFile("/my/path/", 'utf8' ,(err, data) => {
arr = parsing(data);
arr.splice(-1,1);
return arr;
});
}
#2
0
or pass a callback function to final function
或者将回调函数传递给最终函数
function callback(arr) {
//do something with arr
}
function final(callback) {
var arr;
fs.readFile("/my/path/", 'utf8' ,(err, data) => {
arr = parsing(data);
arr.splice(-1,1);
callback(arr);
});
}
As @Farhan Yassen's answer won't result correct behavior due to the async nature.
由于异步性质,@ Farhan Yassen的答案不会导致正确的行为。
And also, you can always use synchronous version of the readFile
with readFileSync
而且,您始终可以将readFile的同步版本与readFileSync一起使用
#1
0
readFile
is async function you need to do this
readFile是你需要执行此操作的异步函数
function final(){
var arr;
fs.readFile("/my/path/", 'utf8' ,(err, data) => {
arr = parsing(data);
arr.splice(-1,1);
return arr;
});
}
#2
0
or pass a callback function to final function
或者将回调函数传递给最终函数
function callback(arr) {
//do something with arr
}
function final(callback) {
var arr;
fs.readFile("/my/path/", 'utf8' ,(err, data) => {
arr = parsing(data);
arr.splice(-1,1);
callback(arr);
});
}
As @Farhan Yassen's answer won't result correct behavior due to the async nature.
由于异步性质,@ Farhan Yassen的答案不会导致正确的行为。
And also, you can always use synchronous version of the readFile
with readFileSync
而且,您始终可以将readFile的同步版本与readFileSync一起使用