javascript - 带有重复逻辑附加到同一项目数组的 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
解决方案
我相信你可以从问题中看到你有链接承诺的缺点 - 也许类似于我下面使用的方法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()
推荐阅读
- python - Python。无法根据深度优先搜索的结果构建树(给定每个节点的高度)。不知道回溯时有什么问题
- node.js - 带有猫鼬的 PassportJS 只发送一半的数据
- r - 如何在某些行上添加/删除计算百分比
- r - 在命名列之后选择列
- javascript - 从链接下载文件并检查下载是否完成nodejs
- xml - 从 .xsd 文件创建 xml 文件的用户友好方式 *无需为用户编码*
- javascript - React 中的 App.js 文件是什么?文件太长?
- amazon-web-services - AWS CDK 应用程序如何“引用”已经创建的 aws lambda 函数(而不在堆栈中创建一个新函数)?
- docker - 使用公司签名证书时,Docker nginx 连接被拒绝(端口 80 和 443)
- arrays - 我们是否应该在对数组执行操作之前对数组进行排序?