将两个不同的 Fetch 调用与来自 Jsonplaceholder.com 的数据合并



我正在尝试合并或基本上对https://jsonplaceholder.typicode.com/commentshttps://jsonplaceholder.typicode.com/posts提供的两个数据集执行内部连接。连接当然会分别使用两个数据集的PostId键和id键;但是我不确定如何实际做到这一点。我添加了我的代码笔:https://codepen.io/gabedesigns/pen/qMGgxY?editors=1111,我似乎收到一个错误,说我的构造函数缺少"(("。弄清楚这一点后,我还需要搜索带有提供的帖子ID的帖子以及与帖子相对应的评论。也许我需要嵌套循环才能使其工作?我试图查找有关此的其他一些信息,但似乎找不到太多。如果我可能跳过了任何其他资源,请不要害怕在下面链接它。我在这里看到一篇关于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}));
}

这里有几个问题。我认为您可能在尝试将 promise 传递到您的排序函数而不是等待它解析时与 fetch 的异步性质相冲突,将它们收集到 Promise.all 批处理中是处理此问题的一种方法。另外,正如您在评论中对两个同名变量使用解构时指出的那样,这里的两个简单解决方案是不要解构或使用别名。希望这有帮助

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>

相关内容

最新更新