[英]Function is being called before await finishes
我正在尝试使用 async/await 进行一些操作,出于某种原因,我的 function 在等待完成之前运行,有人可以告诉我为什么吗?
(function() { var posts = [{ title: "Post 1", body: "This is post 1" }, { title: "Post 2", body: "This is post 2" }, { title: "Post 3", body: "This is post 3" } ]; function GetPosts() { setTimeout(() => { let output = ''; posts.forEach((post, index) => { output += `<li>${post.title}</li>`; }); document.body.innerHTML = output; }, 1000); } function CreatePost(post) { setTimeout(() => { posts.push(post); }, 4000); } async function init() { await CreatePost({ title: "Post 4", body: "This is post 4" }); GetPosts(); } init(); })();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
由于setTimeout
不返回任何 promise。 它不会等到CreatePost
function 被执行。 因此,将相同的东西包装在 Promise 中将有助于提供您正在寻找的 output。
(function() { var posts = [{ title: "Post 1", body: "This is post 1" }, { title: "Post 2", body: "This is post 2" }, { title: "Post 3", body: "This is post 3" } ]; function GetPosts() { setTimeout(() => { let output = ''; posts.forEach((post, index) => { output += `<li>${post.title}</li>`; }); document.body.innerHTML = output; }, 1000); } //Wrap this with a new promise function CreatePost(post) { return new Promise((resolve, reject) => { setTimeout(() => { posts.push(post); resolve(); }, 3000); }) } async function init() { await CreatePost({ title: "Post 4", body: "This is post 4" }); GetPosts(); } init(); })();
如果你想使用async
, await
是promise
(function () { var posts = [{ title: "Post 1", body: "This is post 1" }, { title: "Post 2", body: "This is post 2" }, { title: "Post 3", body: "This is post 3" } ]; function GetPosts() { return new Promise(resolve => { setTimeout(() => { let output = ''; posts.forEach((post, index) => { output += `<li>${post.title}</li>`; resolve('success'); }); document.body.innerHTML = output; }, 1000); }) } function CreatePost(post) { return new Promise((resolve) => { setTimeout(() => { posts.push(post); resolve('success') }, 4000); }) } async function init() { const a = await CreatePost({ title: "Post 4", body: "This is post 4" }); const b = await GetPosts(); return b } init(); })();
function CreatePost(post) {
//setTimeout is non-blocking
setTimeout(() => {
posts.push(post);
}, 4000);
}
您基本上不会等待帖子被推送到列表中。 这就是它没有显示的原因。 如果 GetPosts 中的间隔小于 CreatePost 中的 on ,则它会显示。 它与异步/等待无关。 对 CreatePost 的调用首先不是异步的,因为您没有返回 Promise 。 第二件事是 setTimeout 不会阻塞,所以后面运行的每一个代码基本上都可以在回调被调用之前完成。
要使 CreatePost 真正异步,只需查看在等待完成之前调用 @axiac Function的答案注意:setTimeout 仍然是非阻塞的,代码不会按预期工作。 如果这不仅仅是锻炼,我会说摆脱 setTimeouts。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.