首页 > 解决方案 > 带有重复逻辑附加到同一项目数组的 Javascript 承诺链接

问题描述

链的各个部分根据结构重复。例如,站点可以有两个子站点,每个子站点都有两个列表。这意味着最后一个链将触发四次。在执行了所有内部更改之后,我在哪里/如何获取模板对象,以便我拥有完整的模板集合?

    let promises = [];
    let templates:ITemplate[] = [];

    pnp.sp.web.webs.get().then(sites => {
      sites.forEach(site => {
        pnp.sp.site.openWebById(site.Id).then(result => {
          result.web.lists.get().then(lists => {
            lists.forEach(list => {
              promises.push(result.web.lists.getByTitle(list.Title).items.get());
            });
            Promise.all(promises)
            .then((results) => {
               // This runs multiple times which makes sense but I need the final templates array
               results.forEach(items => {
                items.forEach(item => {            
                  let template:ITemplate= {
                    Title:item.Title,
                    ...
                    ...
                  };
                  templates.push(template);
                });

                // If I add function here it runs multiple times which is not the desired outcome
                doSomethingWithTemplates(templates);
              });
            })
          })
        })
      });
    })

// Then do something with templates item collection that is a single item array with all items

标签: javascripttypescript

解决方案


我相信你可以从问题中看到你有链接承诺的缺点 - 也许类似于我下面使用的方法async/await可以更清楚地解决你的问题?

Async/await有效地建立在 Promise 之上,并且仍然使用 Promise。如果您还不知道,这会给您一个想法。

async function insertName():Promise<ITemplate[]> {
    let promises = [];
    let templates:ITemplate[] = [];
    const sites = await pnp.sp.web.webs.get()
    sites.forEach(site => {
        const result = await pnp.sp.site.openWebById(site.Id)
        const lists = await result.web.lists.get()
        lists.forEach(list => {
            const toPush = await result.web.lists.getByTitle(list.Title).items.get()
            promises.push(toPush);
        })
        const results = await Promise.all(promises)
        results.forEach(items => {
            items.forEach(item => {            
                let template:ITemplate= {
                    Title:item.Title,
                    ...
                    ...
                };
                templates.push(template);
            });
            doSomethingWithTemplates(templates);
        });
    })
    return templates
}
const templates: ITemplate[] = await insertName()

推荐阅读