【问题标题】:adding async values to array using forEach [duplicate]使用 forEach 将异步值添加到数组 [重复]
【发布时间】:2021-02-15 13:29:59
【问题描述】:

我正在尝试在对象数组中创建过滤数组。我这样做是通过在 forEach 中运行 case switch 并派生一个将其附加到新对象的新数组并将该对象推送到存储在 foreach 之外的数组来实现的。但是在运行 foreach 之后,外部数组的长度仍然显示为 0,等式的其余部分与所述数组的处理有关。它有两个非常大的代码块,所以我试图编辑一些。

let updatedDrop = []
  drop.forEach(async(tollFree) => {

      const zipCodes = Object.values(tollFree)[0].split(",");
   

      let updatedList = []
      const {
        tracking,
        mailList,
      } = tollFree;

   zips = await Zip.find({
    "class": { "$in": zipCodes },
  });
   
  zips = zips.map(zip => zip.zip4)

switch (zipCodeSuppress) {
  case "keepSelect":
   (insert case switch)
    break;
}

  const distinct = (value, index, self) => {
    return self.indexOf(value) === index;
  };
      updatedList = updatedList.flat()

      updatedList = updatedList.filter(distinct)
      

   const combinedCost = unitCost + postageCeiling
   const  dropItem = {
        updatedList,
        tracking,
     } 
      
     updatedDrop.push(dropItem)

     //console.log(dropItem)
    })


console.log(updatedDrop.length)

  let advJobs = [];
  let cspJobs = [];
  let wbJobs = [];
if (updatedDrop.length > 0){ ..... 

所以在我能够访问更新的异步数据之前,公式的其余部分都会停止。我该怎么做?

【问题讨论】:

    标签: javascript arrays foreach async-await


    【解决方案1】:

    你面临的问题是forEach回调并没有阻塞主线程,所以当你在forEach声明后立即访问数组时,里面的回调没有完成执行。

    看看这个例子

    const timer = 2000;
    const numbers = [1, 2, 3];
    const emptyArray = [];
    
    async function getNumberTwo() {
      return new Promise((resolve) => {
        setTimeout(() => resolve(2), timer);
      });
    }
    
    async function withForEach() {
      numbers.forEach(async (n) => {
        const two = await getNumberTwo();
        emptyArray.push(n + two);
      });
      console.log(emptyArray); // the array is empty here.
      setTimeout(() => console.log(emptyArray), numbers.length * timer); // if I log the array after all the time has gone, the array has the numbers.
    }
    
    withForEach()
    

    但是现在如果你使用 for of,或者甚至是普通的 for 我会说

    // all the declarations from before..
    
    async function withForOf() {
      for (const number of numbers) {
        const two = await getNumberTwo();
        emptyArray.push(number + two);
      }
    
      console.log(emptyArray); // now the array has what you expect it to have
    }
    
    withForOf()
    

    因此,总而言之,您可以使用普通的forfor of 使其按需要工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 2020-10-13
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多