2017-10-14 49 views
0

這是一個函數,它解析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? 
} 
+0

你定義usbDevicePrefix地方? – Nick

+1

[我如何從異步調用返回響應?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – PMV

+0

@snapjs是的,我在上面定義了它。有沒有錯誤,當我運行該代碼 – eric

回答

1

fs.readdirasync函數,它接受一個回調。

您可以傳播該回調:

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