2017-10-14 4 views
0

これは、ラズベリーパイの/devフォルダからすべてのUSBドライブを解析する機能です。 sdaada1sdbsdb1を配列として返したいが、失敗する。 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.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

ちょっと@アーロン、それは非常に便利です。私はjavascriptにはかなり新しいですし、私はあなたのコードについて見ていますが、 – eric

関連する問題