setTimeOut()以意想不到的方式工作



我刚开始尝试异步JS与setTimeout()函数。我在JS数组中硬编码了两个对象,并添加了一个在3S延迟中运行的方法。我编写了另一个方法来打印数组(HTML Response和Console.log)。打印响应似乎工作得很好,那仍然是posts.push(post)调用,只有两个对象被写入HTML响应。

但有时console.log()打印3个对象,要么在"begin "或者有时甚至在addPost()调用之前,而addPost仅在5000ms之后调用。不知道我做错了什么。有人能帮忙吗?

const posts = [{
body: "I am Post One",
title: "Post One"
},
{
body: "I am post two",
title: "Post Two"
}
]
function addPost(post) {
setTimeout(function() {
console.log("begin addpost");
let output = "<p> ";
posts.forEach(function(post) {
output += (post.body + "<br/>");
});
output += "</p>";
document.body.innerHTML = output;
posts.push(post);
console.log("end addpost");
}, 5000);
}
function getPosts() {
setTimeout(function() {
console.log("begin getpost");
console.log(posts);
console.log("end getpost");
}, 1000);
}
console.log(posts);
addPost({
body: "I am  post Three",
title: "Post Three"
});
getPosts();

我认为这一行就是为什么你的控制台打印3个对象而不是两个的原因。

posts.push(post);

这是当你没有重新初始化posts对象时造成的。(这实际上需要你重新加载)。我不确定这是你所面临的真正问题,但几分钟后阅读你的代码,我没有看到任何其他的可能性。

此外,如果您正在尝试使用JavaScript进行异步操作,这可能是一种更短、更简洁的方法:

const posts = [{
body: "I am Post One",
title: "Post One"
},
{
body: "I am post two",
title: "Post Two"
}
]
async function wait(ms) {
// please do read more about Promise & arrow function to understand the syntax.
return new Promise(_ => setTimeout(_, ms));
}
const getPost = async () => {
await wait(1000);
console.log("begin getpost");
console.log(posts);
console.log("end getpost");
}
const printPost = async () => {
await wait(4000);
console.log("begin addpost");
let output = "<p> ";
posts.forEach(function(post) {
output += (post.body + "<br/>");
});
output += "</p>";
document.body.innerHTML = output;
console.log("end addpost");
}
(async () => {
getPost();
printPost();
})();

这样更容易读懂。祝你玩得开心!

最新更新