这是一个解析 Raspberry Pi 的 /dev
文件夹中所有 USB 驱动器的函数。我想将 sda
、ada1
、sdb
、sdb1
作为数组返回,但未能这样做。当我执行 console.log(readDeviceList())
时,它不会打印任何内容。我的代码有什么问题吗?
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);
};
});
}
或者将其包装在 promise 中,这样更容易维护:
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
});
关于JavaScript 代码不返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46740414/