简体   繁体   English

在循环内调用 function

[英]Call function inside a loop

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:我有一个对象数组,我需要将它们一个一个地传递给 function,但我想在数组中的每个项目之间暂停 1 秒:

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.我需要这样做,因为更改“setFiltro”时会调用 2 个函数,这需要几毫秒。 Because of that the function is only doing what it has to do with the last index of the array因此,function 只做与数组的最后一个索引有关的事情

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.以下将快速连续调用MontagemFiltro ,对NumerosEtiquetas中的每个项目执行一次,并返回一个 promise ,当所有异步任务完成后,它将解析为一组结果。 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 */ )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM