[英]Javascript promise chaining with repeating logic appending to same item array
链的各个部分根据结构重复。 例如,站点可以有两个子站点,每个子站点都有两个列表。 这意味着最后一个链将触发四次。 在执行了所有内部更改之后,我在哪里/如何获得模板 object 以便我拥有完整的模板集合?
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
我相信你可以从问题中看到你有链接承诺的缺点 - 也许类似于我下面使用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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.