问题描述
我已经学习了 2 周的 Javascript,现在我正在学习 Javascript 中的 promise,在课程中做了一些示例,但我在这里遇到了一些问题。那里的 forEach() 方法正在工作
data.comments.forEach(function (comment) {
var user = data.users.find((user) => user.id === comment.userId);
html += `<li>${user.name}: ${comment.content}</li>`;
});
但是下面的 forEach() 方法不起作用
data.comments.forEach((comment) => {
var user = data.users.find((user) => {
return user.id === comment.userId;
});
html += `<li>${user.name}: ${comment.content}</li>`;
});
这是我的源代码
var users = [
{
id: 1,name: "User 1",},{
id: 2,name: "User 2",];
var comments = [
{
id: 1,userId: 1,content: "Content written by User id 1",userId: 2,content: "Content written by User id 2",];
function getUserByIds(userIds) {
return new Promise((resolve) => {
var results = users.filter((user) => userIds.includes(user.id));
setTimeout(() => resolve(results),2000);
});
}
function getComments() {
return new Promise((resolve) => {
setTimeout(() => resolve(comments),2000);
});
}
getComments()
.then((comments) => {
var userIds = comments.map((comment) => {
return comment.userId;
});
return userIds;
})
.then((userIds) => {
return getUserByIds(userIds);
})
.then((users) => {
return {
users: users,comments: comments,};
})
.then((data) => {
var commentBlock = document.querySelector("#comment-block");
var html = "";
// data.comments.forEach((comment) => {
// var user = data.users.find((user) => {
// return user.id === comment.userId;
// });
// html += `<li>${user.name}: ${comment.content}</li>`;
// });
data.comments.forEach(function (comment) {
var user = data.users.find((user) => user.id === comment.userId);
html += `<li>${user.name}: ${comment.content}</li>`;
});
commentBlock.innerHTML = html;
});
为什么这不适用于 ES6 箭头函数? 谢谢大家,
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)