2 回答
TA贡献1869条经验 获得超4个赞
您的var pathNodesArray = [];范围不对。您希望每条路径都有自己的路径节点数组,虽然pathNodesArray = [];在循环中执行顺序操作可能有效,但在并行处理路径时会失败。const更喜欢var:
const PathNode = require('../models/pathNode');
const Path = require('../models/path');
const repository = require('../../repository');
const jsonConverted = JSON.parse(convert.xml2json(req.file.buffer.toString(), { compact: true, spaces: 4, alwaysChildren: true }));
const paths = jsonConverted.GlDocumentInfo.world.GlDocument.GlDocumentNetwork.Network.Paths.Path;
await Promise.all(paths.map(async path => {
const pathNodesArray = [];
// ^^^^^ declare inside each iteration
await Promise.all(path.PathNodes.PathNode.map(async pathNode => {
const newPathNode = new PathNode({
key: pathNode._attributes.key,
node: pathNode._attributes.Node,
duration: pathNode._attributes.Duration,
distance: pathNode._attributes.Distance,
});
pathNodesArray.push(newPathNode.key);
await repository.savePathNode(newPathNode);
// ^^^^^
}));
const newPath = new Path({
key: path._attributes.key,
isEmpty: path._attributes.IsEmpty.toString().toLowerCase(),
pathNodes: pathNodesArray,
});
await repository.savePath(newPath);
// ^^^^^
}));
// … doesn't matter for this question
TA贡献1909条经验 获得超7个赞
尝试添加return之前repository.savePathNode(newPathNode)。现在,它接缝了,你的嵌套承诺没有被等待
...
await Promise.all(path.PathNodes.PathNode.map(async pathNode => {
var newPathNode = new PathNode();
newPathNode.key = pathNode._attributes.key;
newPathNode.node = pathNode._attributes.Node;
newPathNode.duration = pathNode._attributes.Duration;
newPathNode.distance = pathNode._attributes.Distance;
pathNodesArray.push(newPathNode.key);
return repository.savePathNode(newPathNode);
}))
...
添加回答
举报