JavaScript代码不返回数组
问题描述:
这是一个函数,它解析Raspberry Pi的/dev
文件夹中的所有USB驱动器。我想返回sda
,ada1
,sdb
,sdb1
作为一个数组,但未能这样做。当我做console.log(readDeviceList())
时,它不打印任何东西。我的代码有什么问题?JavaScript代码不返回数组
var usbDeviceList = new Array();
function readDeviceList() {
var usbDeviceList = new Array();
fs.readdir(deviceDir, function (error, file) {
if (error) {
console.log("Failed to read /dev Directory");
return false;
} else {
var usbDevCounter = 0;
console.log("Find below usb devices:");
file.forEach(function (file, index) {
if (file.indexOf(usbDevicePrefix) > -1) {
usbDeviceList[usbDevCounter++] = file;
}
});
console.log(usbDeviceList); // This prints out the array
};
});
console.log(usbDeviceList); // This does not print out the array
return usbDeviceList; // Is this return value valid or not?
}
答
fs.readdir
为async
函数,它接受一个回调。
您可以传播该回调:
function readDeviceList(callback) {
var usbDeviceList = new Array();
fs.readdir(deviceDir, function (error, file) {
if (error) {
callback(null, error);
} else {
// ...
callback(usbDeviceList, null);
};
});
}
或者在一个承诺,这是更容易维护它包:
function readDeviceList() {
var usbDeviceList = new Array();
return new Promise((resolve, reject) => {
fs.readdir(deviceDir, function (error, file) {
if (error) {
reject(error);
} else {
// ...
resolve(usbDeviceList);
};
});
});
}
用法:
// Callback
readDeviceList(function (usbDeviceList, error) {
if (error) {
// Handle error
} else {
// usbDeviceList is available here
}
});
// Promise
readDeviceList.then(function (usbDeviceList) {
// usbDeviceList is available here
}).catch(function (error) {
// Handle error
});
+0
嘿@aaron,这是非常有用的。我对JavaScript很陌生,我会看看你的代码, – eric
你定义usbDevicePrefix地方? – Nick
[我如何从异步调用返回响应?](https://*.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – PMV
@snapjs是的,我在上面定义了它。有没有错误,当我运行该代码 – eric