简体   繁体   中英

execute code after callback function finish

i want to execute addFormLayoutSectionFieldsView() function after all callback finish in this code Ts file

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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