JavaScript代码不返回数组

时间:2017-10-14 02:58:48

标签: 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?
}

1 个答案:

答案 0 :(得分:1)

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
});