我目前有以下代码从API提取数据并将其解析到我的数据库中。这最多需要5分钟,因为一天可能有多达50场比赛,每场比赛都有十几个独立的项目,每个项目最多有20名选手。把它想象成一场田径比赛。有时这个脚本要插入10,000行。
// Create Meetings
for (const meeting of meetingList) {
const newMeeting = await createMeeting(meeting);
// Create/Update Events
for (const event of meeting.events) {
await createEvent(event, newMeeting.id);
// Create/Update Competitors
for (const competitor of event.competitors) {
await createCompetitor(competitor);
await createRacingEventCompetitor(competitor, event.id);
}
}
}
以前,我使用promise . allsettle()作为并行发出请求的好方法,节省了大量时间。当你在我的例子中有嵌套循环时,我如何做同样的事情?
简单地创建一个数组来保存承诺,例如称为promises
然后将每个请求推送到该数组,而不是等待它
并等待promise . allsettle (promises)
注意:由于内部请求需要newMeeting
,您仍然需要等待…不过,也有一种方法可以避免这种情况
但是,这是一个开始
const promises = [];
for (const meeting of meetingList) {
const newMeeting = await createMeeting(meeting);
for (const event of meeting.events) {
promises.push(createEvent(event, newMeeting.id));
for (const competitor of event.competitors) {
promises.push(createCompetitor(competitor));
promises.push(createRacingEventCompetitor(competitor, event.id));
}
}
}
await Promise.allSettled(promises);
不确定这是使所有东西平行的最好方法,但这是一种方法
const promises = [];
for (const meeting of meetingList) {
promises.push(
createMeeting(meeting)
.then(newMeeting => {
const innerPromises = [];
for (const event of meeting.events) {
innerPromises.push(createEvent(event, newMeeting.id));
for (const competitor of event.competitors) {
innerPromises.push(createCompetitor(competitor));
innerPromises.push(createRacingEventCompetitor(competitor, event.id));
}
}
return Promise.allSettled(innerPromises);
})
);
}
await Promise.allSettled(promises);