infodev
infodev

Reputation: 5245

Transforme synchronous Map method to async traitment

I have a huge amont of data to transform into new format.

Actually I'm using map method but as it's syncronous and it's affecting performances.

dataFormatted = cmtAllRawdataDB[0].rows.map(elm => new Message(elm, configResult));

For information Message class have globally this format:

export class Data {
  public value: string;
  public date: Date;
  constructor(dbData) {
    this.value = '123';
  }
}

export class Measure {
  public name: string;
  public unit: string;
  public data: Data[];
  constructor(config, dbData) {
    this.name = config.name;
    this.unit = config.value;
    ...
    this.data = [new Data(dbData)];
  }
}

export class Sensor {
  public id: string;
  public label: string;
  public measures: Measure[] = [];
  constructor(dbData, config) {
    this.id = '123';
    this.label = 'SensorType';
    config.unitConfig.map(elm => this.measures.push(new Measure(elm, dbData)));
  }
}

export class Message {
  public id: string;
  ...
  public sensors: Sensor[];
  constructor(dbData: any, config: any) {
    this.id = dbData.value._id;
    ....
    this.sensors = [new Sensor(dbData, config)];
    console.log(this.id, this.arrivalTimestamp);
  }
}

Is there a way to run asynchronously this code ?

Upvotes: 1

Views: 29

Answers (2)

Osama
Osama

Reputation: 3040

Use async and await keywords like this way

async getDataFormatted(){     return(cmtAllRawdataDB[0].rows.map(elm => new Message(elm, configResult)));
}

let dataFormatted= await getDataFormatted();

Upvotes: 1

Akash Salunkhe
Akash Salunkhe

Reputation: 2945

Just put this operation inside function and put it inside settimeout method, for just 10 millisecond

var example = () => {
  setTimeout(() => {
    return (dataFormatted = cmtAllRawdataDB[0].rows.map(
      elm => new Message(elm, configResult)
    ));
  }, 10);
};

Upvotes: 2

Related Questions