顺序遍历数组

时间:2018-07-31 03:55:24

标签: javascript arrays

我试图遍历一个数组,然后将该数组的项目推到变量/对象(tempComponents)中。然后在执行tempComponents之前对storeNewComponents重新排序。当我遍历数组时,我正在进行API调用以获取响应以推送到tempComponents

我在这里的方法是,当循环到达末尾(i = array["steps"].length)时,它将执行storeNewComponents。但是,当我运行循环时,它不会按顺序遍历数组,因此storeNewComponents不会在最后执行(遍历数组的顺序每次都不同)。

这是为什么?如何确保循环按顺序遍历数组?

array: {
    steps: [a, b, c, d]
}

tempComponents: {
    components_under_section: []
}


    loopReorderStore(){
        for (let i = 0; i < array["steps"].length; i++){
          this.generateBlankComponent({
            componentType: 'Composition',
            options: {
              title: array["steps"][i],
              content: "sample sample"
            }
          })
          .then( (componentData) => {
            let componentPath = "/projects/" + this.currentLessonId + "/components"
            this.apiPost({ path: componentPath, data: {"component": componentData} })
            .then( (componentResponse) => {
              console.log("componentResponse: " + JSON.stringify(componentResponse))

              // add to tempComponents
              this.tempComponents.components_under_section.push(componentResponse.data)
              console.log("tempComponents after creating component: " + JSON.stringify(this.tempComponents))

              // reorder tempComponents
              this.reorderComponents(this.tempComponents)
              console.log("tempComponents after reordering: " + JSON.stringify(this.tempComponents))

              if (i === (array["steps"].length - 1)) {
                this.storeNewComponent(this.tempComponents)
              }
            })
          })
        }
       }

1 个答案:

答案 0 :(得分:1)

您要为每个元素启动一个异步API调用,然后在所有元素完成后,启动this.storeNewComponent。为此,请收集您在循环中创建的承诺,然后使用Promise.all(promises).then(...)启动装订器。

let promises = array.steps.map(step =>
  return this.generateBlankComponent(...)  // return a promise to `promises`
  .then(componentData => {
    ...
    return this.apiPost(...)     // return a promise to allow chaining
    .then(componentResponse => {
      ...
      return tempComponent;      // return the value itself
    });
  });
});

Promise.all(promises)            // wait on each promise, and its chain
.then(tempComponents => {        // and get the array of results that parallels
  this.storeNewComponent(tempComponents);  // the original array of inputs
});

(请确保不要忘记我添加的所有return语句,这对于确保正确的值滴到Promise.all之后是至关重要的。)

相关问题