如何解决为什么 forEach() 方法在 Promise 对象箭头函数 ES6 中不起作用?
我已经学习了 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 举报,一经查实,本站将立刻删除。