我正在尝试对https://jsonplaceholder.typicode.com/comments
和https://jsonplaceholder.typicode.com/posts
提供的两个数据集进行合并或基本上执行内部联接。当然,联接将分别使用两个数据集的PostId
和id
键;但是我不确定如何实际执行此操作。我添加了我的代码笔:https://codepen.io/gabedesigns/pen/qMGgxY?editors=1111,并且似乎收到一条错误消息,说我缺少构造函数的'()'。弄清楚这一点之后,我还需要搜索具有提供的帖子ID和与该帖子对应的评论的帖子。也许我需要嵌套for循环才能使它工作?我试图查找有关此问题的其他信息,但似乎找不到太多。如果还有其他资源我可能已经跳过,请不要害怕在下面链接。我在这里看到一个帖子已经在谈论使用javascript而不是SQL进行“内部连接”,但这是我遇到的一些问题。这是一些代码:
function getResults() {
const equijoin = (xs, ys, primary, foreign, sel) => {
const ix = xs.reduce((ix, row) => ix.set(row[primary], row), new Map());
return ys.map(row => sel(ix.get(row[foreign]), row));
};
const postData = fetch("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
return response.json();
});
const commentData = fetch("https://jsonplaceholder.typicode.com/comments")
.then(function(response) {
return response.json();
});
const result = equijoin(postData, commentData,"id", "postId", ({title,
body}, {name,body}) => ({title,body,name}));
}
答案 0 :(得分:3)
这里有两个问题。我认为您可能一直在尝试将承诺传递给您的排序函数而不是等待其解决,而是将它们收集到Promise中,这与fetch的异步性质不符。所有批处理都是处理此问题的一种方法。同样,正如某人在评论中所指出的那样,您正在对具有相同名称的两个变量使用解构,这里的两个简单解决方案是不解构或使用别名。希望这会有所帮助
function getResults() {
const checkResult = res => res.ok ? res.json() : Promise.resolve({});
const joinMap = ({title, body:lbody}, {name,body:rbody}) => ({title,lbody, rbody,name});
const equiJoin = (xs, ys, primary, foreign, sel) => {
const ix = xs.reduce(
(ix, row) => ix.set(row[primary], row), new Map()
);
return ys.map(row => sel(ix.get(row[foreign]), row));
}
const posts = fetch("https://jsonplaceholder.typicode.com/posts")
.then(checkResult);
const comments = fetch("https://jsonplaceholder.typicode.com/comments")
.then(checkResult);
return Promise.all([posts, comments])
.then(([postData, commentData]) => {
const result = equiJoin(postData, commentData,"id", "postId", joinMap);
console.log(result);
})
.catch(err => console.error(err));
}
button {
background-color: white;
color: black;
border: 2px solid #555555;
border-radius: 4px;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
button:hover {
background-color: #555555;
color: white;
}
input {
width: 20vw;
height: 10vh;
padding: 0.5%;
border-radius: 4px;
border: 1px solid black;
}
#results {
position: absolute;
border: 1px solid gray;
height: 60vh;
width: 60vw;
left: 20vw;
top: 10vw;
}
<input type="text" id="postIDinput" placeholder="Post ID" required="true"></input>
<button type="submit" onclick="getResults()">Submit</button>
<div id="results"></div>