[英]async/await example not working. What am I doing wrong
I am trying to learn the concepts of async/await in javascript. 我正在尝试学习javascript中异步/等待的概念。 I tried a simple code, to wait for a create post function to finish before calling the getPosts function, but the newly created post is not showing up. 我尝试了一个简单的代码,在调用getPosts函数之前要等待create post函数完成,但是新创建的post没有出现。 This is what I have tried out. 这就是我尝试过的。
const posts = [{ title: "Post One", body: "This is post one" }, { title: "Post Two", body: "This is post two" } ] const newpost = { title: "Post Three", body: "This is post three" } function getPosts() { setTimeout(() => { let output = ''; posts.forEach((post, index) => { output += `<li>${post.title} : ${post.body}</li>`; }); document.body.innerHTML = output; }, 1000); } function createPost(post) { setTimeout(() => { posts.push(post); }, 2000); } async function init() { await createPost(newpost); getPosts(); } init();
Can anyone point out what I am doing wrong? 谁能指出我做错了什么?
createPost should return promise like below createPost应该返回promise,如下所示
function createPost(post) {
return new Promise((resolve,reject)=> {
setTimeout(() => {
posts.push(post);
resolve();
}, 2000);
});
}
The problem is that createPost
doesn't return a promise. 问题在于createPost
不会返回承诺。
You can either return a promise manually: 您可以手动返回承诺:
function createPost(post) {
return new Promise((resolve) => {
setTimeout(() => {
posts.push(post);
resolve();
}, 2000);
});
}
But who want's to create promises by hand 😉? 但是谁愿意手工创造诺言😉? And since you want to practice with async functions, have createPost
be an async function by itself. 并且由于您要练习异步功能,因此请让createPost
本身就是一个异步功能。
I'm also extracting the setTimeout
calls to a small wait
async utility function: 我还将setTimeout
调用提取到一个小的wait
异步实用程序函数中:
const posts = [{ title: "Post One", body: "This is post one" }, { title: "Post Two", body: "This is post two" } ] const newpost = { title: "Post Three", body: "This is post three" } const sleep = time => new Promise(resolve => setTimeout(resolve, time)); async function getPosts() { await sleep(1000); let output = ''; posts.forEach((post, index) => { output += `<li>${post.title} : ${post.body}</li>`; }); document.body.innerHTML = output; } async function createPost(post) { await sleep(2000); posts.push(post); } async function init() { await createPost(newpost); getPosts(); } init();
May I know why you're using setTimeout()
function? 我可以知道为什么要使用setTimeout()
函数吗? removing the setTimeout()
makes the code just work fine 删除setTimeout()
可使代码正常运行
const posts = [{
title: "Post One",
body: "This is post one"
},
{
title: "Post Two",
body: "This is post two"
}
]
const newpost = {
title: "Post Three",
body: "This is post three"
}
function getPosts() {
let output = '';
posts.forEach((post, index) => {
output += `<li>${post.title} : ${post.body}</li>`;
});
document.body.innerHTML = output;
}
function createPost(post) {
posts.push(post);
}
async function init() {
await createPost(newpost);
getPosts();
}
init();
Here is the working code pen: Code Pen Link 这是工作代码笔: 代码笔链接
createPost should return a promise so the function should be like that createPost应该返回一个Promise,所以函数应该像这样
function createPost(post) {
return new Promise( resolve =>
setTimeout(() => {
posts.push(post);
resolve()
}, 2000);
});
}
The await command expects the calling function to return a promise. await命令期望调用函数返回一个promise。 Such a function usually execute an asynchronous command and resolves the promise when the command is successful. 这样的函数通常执行异步命令,并在命令成功时解决承诺。
var posts = []; function createPost(post) { return new Promise(function(resolve, reject){ setTimeout(() => { posts.push(post); resolve(); //<- resolved the promise here }, 2000); }) } async function testAsync() { await createPost('a post'); console.log(posts) } testAsync();
In this case, although Array.push() doesn't do any async operation, you call it via setTimeout
to do it in an async fashion. 在这种情况下,尽管Array.push()不执行任何异步操作,但是您可以通过setTimeout
调用它以异步方式进行操作。
Async/await only works with promises, so you need to wrap whatever code you have in createPost()
in a promise, return it and then resolve it to indicate that it doesn't have to be awaited anymore and the code can continue executing. 异步/等待仅适用于promise,因此您需要将在createPost()
中拥有的所有代码包装在promise中,将其返回,然后对其进行解析以表明不再需要等待它,并且代码可以继续执行。 I made a tiny example from your code where you can see how it works: 我从您的代码中举了一个小例子,您可以看到它的工作原理:
function getPosts(){ setTimeout(()=>{ console.log( "get posts" ); }, 1000); } function createPost(post){ return new Promise( res => { setTimeout(()=>{ console.log( "post created" ); res(); }, 2000); } ); } async function init(){ await createPost(); getPosts(); } init();
createPost is not any async function, await will listen only to promise and async function, to be able to await that kind of setTimeout, and to apply ur intent, u need promise with done method to tell Nodejs to end listening createPost不是任何异步函数,await将仅侦听promise和async函数,以便能够等待这种setTimeout并应用您的意图,您需要promise与done方法一起告诉Nodejs结束侦听
function createPost(post) {
return new Promise(done){
setTimeout(() => {
posts.push(post);
done()
}, 2000);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.