0

I'm trying to parse a list of valid serial devices so I can output them to a UI, but try as I might, the array that's returned at end of this function is not passed properly. I end up with conflictng results coming from console.log() and my developer console.

Here's the function itself.

function listValidDevices(){ // gets a list of valid devices with vid, pid, and com name
        var parsedDeviceInfo = []
        var rawDeviceInfo = []
        parsedDeviceInfo.size = 0
        SerialPort.list().then((value)=>{
            //console.log(value)
            rawDeviceInfo = value;
            //console.log(rawDeviceInfo)
            for(var i = 0; i < rawDeviceInfo.length; i++){
                if(isSupportedDevice(rawDeviceInfo[i]))
                {
                    //console.log("this device is supported")
                    parsedDeviceInfo.push({deviceName : rawDeviceInfo[i].deviceName, portNumber : rawDeviceInfo[i].comName, pid : rawDeviceInfo[i].productId, vid : rawDeviceInfo[i].vendorId})

                    parsedDeviceInfo.size++
                    console.log(parsedDeviceInfo, parsedDeviceInfo.length)
                    var copy  = parsedDeviceInfo;
                    console.log("copy", copy, "copyLength", copy.length)
                }
            }  
        }, 
        (error)=>{
            console.log(error)
        })
        console.log(parsedDeviceInfo.size)
        return parsedDeviceInfo
    }

Then I call the function like this

var devices = listValidDevices()
console.log(devices, devices.length)

The developer console will show length = 1 and size = 1 (the object I pushed to it also shows up), but console.log() will show length = 0 and size = 0. If I print these values inside of list().then() everything seems to work normally though. Console.log() outputs size 1, and length 1

There has to be something going on under the hood here that I'm just not grasping. Arrays and objects are supposed to be passed by reference in any scenario, and yet here, they apparently aren't.

Carl
  • 457
  • 5
  • 23
  • 1
    It is an asynchronous call the code after it runs before the code in the promise. Basically you ordered a pizza. As soon as you push the submit button, you try to eat the pizza. You do not wait for it to be made and delivered. – epascarello Sep 28 '18 at 16:29
  • pizza sounds good – Mulan Sep 28 '18 at 16:33
  • I think I see what you mean. The promise is asynchronous so the function returns before it does, resulting in the length being zero. this is why the dev console shows a different output from my console.log(). All of this means that I need to wait until the promise is returned before leaving the scope of the function. – Carl Sep 28 '18 at 16:38
  • @epascarello I like the pizza analogy. – parallaxis Sep 28 '18 at 16:41

0 Answers0