-1

I've searched for a solution but I was not able to implement it.

async processMAC(macs){
    let datos = [];
    for(let x in macs){
      await this.ipdataService.getMacsSaData(macs[x]).subscribe(data =>{ 
        datos.push(data)
      }
    )}
    return datos;   
  }


this.processMAC(macs).then(result => {//I want to work with result but it is undefined}
Diego
  • 449
  • 1
  • 6
  • 16

2 Answers2

0

If you are using Promises

async processMAC(macs){
    let datos = [];
    for(let x in macs){
       datos.push(await this.ipdataService.getMacsSaData(macs[x])
    )}
    return datos;   
}

Or if you want to execute getMacsSaData in parallel

function processMAC(macs){
    return Promise.all(macs.map(mac => this.ipdataService.getMacsSaData(mac))) 
}
wiomoc
  • 1,069
  • 10
  • 17
  • Really not equivalent. The first example will await `this.ipdataService.getMacsSaData(macs[x])` one by one. It's async but will take `n * x` amount of time if you'd measure the whole function. The second example does the requests in parallel and returns a promise that resolves when they're all finished. The second example lacks `async/await` as well. See: https://stackoverflow.com/a/45286517/3410196 – Alexander Derck Nov 16 '18 at 11:24
0

Weird, thought there might be some errors in the example code snippet, not sure if this will work:

let macsSaData = await this.ipdataService.getMacsSaData(macs[x]);
macsSaData.subscribe(data => { 
    datos.push(data)
}

Might also be able to put a breakpoint in the callback seeing if the correct data has been pushed into the array.

Cheng
  • 84
  • 1
  • 4