这是情况。我继承了一个很难使用的数据库模式(我们之前都曾到过那里),Node现在更加强调这一点。我需要做的是递归地遍历一条记录的关系(大多数情况下是一次),并在记录的对象等于数组常量中的一组对象(但仅针对该关系链)时停止。所有其他关系都需要继续下去,直到它们达到同一点为止。对于我们的每个部署,关系的数量可能会有所不同,因此无法创建静态解决方案。
gatherDataToSync: async (connection, recordId) => {
self.recordIdsUsed.push(recordId);
let objectId = await referenceHelper.getObjectIdForRecordId(connection, recordId);
let objectData = await self.getRelatedObjectsInformation(connection, recordId);
self.objectCollection.push({
"recordId": recordId,
"objectId": objectId,
objectData
});
if (referenceHelper.includes(self.objectListToStopExecutionAt, objectId) === false) {
let relationships = objectData['relationships'];
if (relationships != null) {
for (let i = 0; i < relationships.length; i++) {
if (referenceHelper.includes(self.relationshipsToIgnore, relationships[i]['id']) === false) {
let relationshipRecordIds = relationships[i]['relationships'];
if (relationshipRecordIds != null) {
for (let j = 0; j < relationshipRecordIds.length; j++) {
if (referenceHelper.includes(self.recordIdsUsed, relationshipRecordIds[j]) === false) {
await self.gatherDataToSync(connection, relationshipRecordIds[j]);
}
}
}
}
}
}
}
},
那是我的递归方法。我需要循环中的所有
await
来完成处理,然后再对gatherDataToSync
函数进行原始调用,以将其诺言返回给从其调用的函数。有办法做到这一点,还是我不考虑这个权利?self.recordIdsUsed
和self.objectCollection
都是模块变量,用于跟踪数据,以免循环中出于比较目的而使数据不同步。如果您需要更多代码,请告诉我,因为我不确定需要什么来理解正在发生的事情。
预先感谢您的帮助!
最佳答案
我不确定以下代码是否对您有用(取决于您如何更改值以及如何基于更改后的值实现referenceHelper.includes
)。问题是您必须返回某些内容,以便gatherDataToSync
的调用者知道它何时完成。
您的代码不返回任何内容,但如果返回await self.gatherDataToSync
,则它将以最慢的方式执行,因为它会堆叠所有异步处理。
gatherDataToSync: async (connection, recordId) => {
self.recordIdsUsed.push(recordId);
//minor improvement maybe, you can do these 2 things in parallel
let [objectId,objectData] = await Promise.all(
referenceHelper.getObjectIdForRecordId(connection, recordId),
self.getRelatedObjectsInformation(connection, recordId)
);
self.objectCollection.push({
"recordId": recordId,
"objectId": objectId,
objectData
});
if (referenceHelper.includes(self.objectListToStopExecutionAt, objectId) === false) {
//you return a recursive promise here so you can await calling gatherDataToSync
return Promise.all(
//no need for if statement and for loop, just take out all items you don't need
(objectData['relationships'] || [])//no need for if null
.filter(//filter out the ones you don't need
item =>
referenceHelper.includes(self.relationshipsToIgnore, item) !== false
)
.map(
item =>
(item['relationships'] || [])//no need for inner if null
.filter(//filter out the ones you don't need
item =>
referenceHelper.includes(self.recordIdsUsed, item) !== false
)
)
.map(
item =>//this is an array of array of objectIds
Promise.all(//create a promise with recursive promises
item.map(
item=>self.gatherDataToSync(connection, item)
)
)
)
);
}
}