JavaScript 代码不返回数组

标签 javascript return

这是一个解析 Raspberry Pi 的 /dev 文件夹中所有 USB 驱动器的函数。我想将 sdaada1sdbsdb1 作为数组返回,但未能这样做。当我执行 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/

相关文章:

javascript - 哪个更好 : Using inbuilt Protractor/selenium functionalities OR Installing other node packages for protractor?

javascript - 无法从 bootStrap 日期选择器读取值

arrays - 如何从 Golang 中的不同函数将一个数组的元素复制到另一个数组

Java让线程返回一些东西给主线程

c - 返回二维数组的问题

javascript - MongoDB 查询从集合中删除重复文档

Javascript递归函数返回未定义而不是预期结果

javascript - 如何使用正则表达式按空格拆分字符串并忽略前导和尾随空格到单词数组中?

flutter - 如何从方法返回两个值

php - 如何从 PHP 方法返回错误?