简体   繁体   English

回调函数完成后执行代码

[英]execute code after callback function finish

i want to execute addFormLayoutSectionFieldsView() function after all callback finish in this code Ts file我想在此代码 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);```

         

To solve this problem I've always used Promise.all alongside map为了解决这个问题,我一直在使用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);
          )```

So here instead of just iterating over all the items and doing new async calls, you are turning each item into a promise, collecting that array of promises with Promise.all , and then when all promises are finished, executing the callback passed to the Promise.all(...).then .因此,这里不是仅仅迭代所有项目并执行新的异步调用,而是将每个项目变成一个承诺,使用Promise.all收集该承诺数组,然后当所有承诺完成后,执行传递给Promise.all(...).then的回调Promise.all(...).then .

For example,例如,

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

That will turn 1 and 2 into promises, and then when both resolve, the console will get logged to.这会将12变成 promise,然后当两者都解决时,控制台将被登录。

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

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