Home > Blockchain >  cant push a promise's value to an array
cant push a promise's value to an array

Time:08-19

when I'm trying to pass the values to an array and return them the console only shows an empty array or say undefined!
my problem is .then don't pass the value to the array

const net = require('net');
const find = require('local-devices');
class Network{
  hostname : string = "";
  port = 80 ;
  deviceList: any = [];

  
  public connect(): void{
      if (net.isIPv4(this.hostname)){
          var connection = net.createConnection({port : this.port, host : this.hostname});
          console.log(connection);
      }
  }
  public findDevices(){
    var boom:object[] = [];
    find().then((devices:any[])=>{
      this.deviceList.push(devices);
    })
    return this.deviceList;
  }

}
const monitor = new Network();
let data = monitor.findDevices();
console.log(data);

CodePudding user response:

I think the reason it's undefined or empty, it's because the function returns earlier than the promise resolves. I made a few edits so the values are correctly resolved, and wrapped it in an async/await function.

const net = require('net');
const find = require('local-devices');

class Network {
  hostname: string = "";
  port = 80;
  deviceList: any = [];


  public connect(): void {
    if (net.isIPv4(this.hostname)) {
      var connection = net.createConnection({ port: this.port, host: this.hostname });
      console.log(connection);
    }
  }
  public findDevices() {
    var boom: object[] = [];
    // Return the promise, so the caller can "await" it
    return find().then((devices: any[]) => {
      // Spread devices, otherwise it will push the array instead of the values
      this.deviceList.push(...devices);
      // Promise return value
      return this.deviceList
    })
  }

}

async function run() {
  const monitor = new Network();
  let data = await monitor.findDevices();
  console.log(data)
}

run()

If you don't want to have the "run" method you can still do as follows:

const monitor = new Network();
monitor.findDevices()
  .then((deviceList) => {
    // This is the return value of the promise
    console.log(deviceList)
    // This is the property deviceList of Network
    console.log(monitor.deviceList)

    // They are both the same
  });

CodePudding user response:

Add async await inside findDevices

  async public findDevices(){
    var boom:object[] = [];
    var devices = await find()
    this.deviceList = devices;
    return this.deviceList;
  }

your existing code is not stopping at find unitil it brings the devices, so its running over before it brings the devices so on adding async await , it will stop until it brings devices

once class is updated with async update then update below code wile executing in end

const monitor = new Network();
monitor.findDevices();
console.log(monitor.deviceList);
  • Related