0

I have an array of objects, I need to pass them one by one to a function, but I want to give a 1sec pause between each item in the array:

async function ChamandoEtiquetas() {
    if(id) {
      if(NumerosEtiquetas) {
        NumerosEtiquetas.forEach(async (Etiqueta) => {
        await  MontagemFiltro(Etiqueta)
        })
      }
    }
 
  }

async function MontagemFiltro(Etiqueta) {
    var CodigoDeBarras = "teste";
           await setFiltro(CodigoDeBarras)
  }

I need to do this, because there are 2 functions that are called when changing the "setFiltro", and it takes a few milliseconds. Because of that the function is only doing what it has to do with the last index of the array

Juan
  • 57
  • 1
  • 5
  • 2
    Aside: Maybe a pad function? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart – Jared Farrish Aug 09 '22 at 14:35
  • Please: `const valor = GuardandoValorCartaoOPMomentaneo.toString(); CodigoDeBarras = valor.padStart(valor.length,'0')` – mplungjan Aug 09 '22 at 14:36
  • I did not know this function, thank you very much for letting me know, I will use it. But that's not the problem – Juan Aug 09 '22 at 14:38
  • Duplicate of [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Samathingamajig Aug 09 '22 at 15:03

1 Answers1

0

Do not insert arbitrary waiting periods. Use promises to wait the precise duration necessary for asynchronous tasks to complete.

The following will call MontagemFiltro, once for each item in NumerosEtiquetas, in rapid succession, and return a promise that will resolve to an array of results when all the asynchronous tasks have completed. Note that this will fail fast if any of the asynchronous calls fails.

function ChamandoEtiquetas(id, NumerosEtiquetas) {
  if(!id || !NumerosEtiquetas) return; // this makes an assumption that ids are strings

  return Promise.all(
    NumerosEtiquetas.map((Etiqueta) => MontagemFiltro(Etiqueta)))    
}

function MontagemFiltro(Etiqueta) {
  var CodigoDeBarras = "teste"
  return setFiltro(CodigoDeBarras)
}

// Usage:
ChamandoEtiquetas(id, NumerosEtiquetas)
  .then((results) => /* do something with the results */ )
Ben Aston
  • 53,718
  • 65
  • 205
  • 331