简体   繁体   中英

How can I make async await work for the attached code?

Can anyone tell me how can I make async await work for the below code:

const posts = [
  { title: "Post One", body: "This is post one" },
  { title: "Post Two", body: "This is post two" },
];

function getPosts() {
  setTimeout(() => {
    posts.forEach((post) => {
      console.log(post.title, post.body);
    });
  }, 1000);
}

function createPost(post) {
  setTimeout(() => {
    posts.push(post);
  }, 2000);
}

async function init() {
  await createPost({ title: "Post Three", body: "This is post three" });
  getPosts();
}

init();

Currently I cannot see the third post as createPost does not wait for getPosts.

Your createPost method should return a Promise and then after setTimeout is executed you can resolve that promise and getPosts method execution inside of init method will then wait for createPost to be resolved.

 const posts = [{ title: "Post One", body: "This is post one" }, { title: "Post Two", body: "This is post two" }, ]; function getPosts() { setTimeout(() => { posts.forEach((post) => { console.log(post.title, post.body); }); }, 1000); } function createPost(post) { return new Promise(resolve => { console.log('called createPost') setTimeout(() => { console.log('resolving createPost') posts.push(post); resolve(true); }, 2000); }) } async function init() { // this will make sure the rest of the code waits for createPost to be resolved await createPost({ title: "Post Three", body: "This is post three" }); // this will only run after createpost is resolved getPosts(); } init();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM