回调函数完成后执行代码

时间:2020-09-04 22:22:38

标签: javascript typescript

我想在此代码Ts文件中的所有回调完成后执行addFormLayoutSectionFieldsView()函数

webPart._getListDataSources(xComp).then((response) => {
            let dItems: List_Item[] = response.value;
            dItems.forEach((item: List_Item) => {
              dataSourceId = item["Id"];
              webPart._getListDataSourceFieldsData(dataSourceId).then((response) => {
                let pItems: List_Item[] = response.value;
                pItems.forEach((item: List_Item) => {
                  AddSectionFieldHtml1 += `<option value= "${item["Id"]}"> ${item["Id"]} </option>`;
                  console.log(AddSectionFieldHtml1);
                });
              });
            });
          });
            
webPart.addFormLayoutSectionFieldsView(FormLayoutSectionId);```

         

1 个答案:

答案 0 :(得分:0)

为解决此问题,我一直将Promise.allmap一起使用

webPart._getListDataSources(xComp).then((response) => {
            Promise.all(response.value.map((item: List_Item) => {
              dataSourceId = item["Id"];
              return webPart._getListDataSourceFieldsData(dataSourceId).then((response) => {
                let pItems: List_Item[] = response.value;
                pItems.forEach((item: List_Item) => {
                  AddSectionFieldHtml1 += `<option value= "${item["Id"]}"> ${item["Id"]} </option>`;
                  console.log(AddSectionFieldHtml1);
                });
              });
            });
          })).then(() =>             
            webPart.addFormLayoutSectionFieldsView(FormLayoutSectionId);
          )```

因此,在这里,您不仅要遍历所有项目并进行新的异步调用,还需要将每个项目变成一个承诺,并用Promise.all收集该承诺数组,然后在所有承诺完成后执行回调传递到Promise.all(...).then

例如,

Promise
  .all([1,2].map(Promise.resolve)
  .then(() => console.log('Done with promises!'))

这会将12变成承诺,然后当两个都解决时,控制台将被登录。