简体   繁体   中英

Variables in promises

I am very new to javascript and I am struggling to understand something.

I have this piece of code:

api.posts
  .browse({ limit: 5, include: 'tags,authors' })
  .then(posts => {
    posts.forEach(post => {
      console.log(post.title)
    })
  })
  .catch(err => {
    console.error(err)
  })

This works fine and on the console I see the 5 post titles. However, I need to create a template with something like this:

<article v-for="post in posts" :key="post">
  <h2>{{ post.title }}</h2>
</article>

but of course "posts" is not accessible as a variable. I tried to add variables inside ".then" but with errors. This might be a basic knowledge, but haven't been able to find a clear answer. Thanks.

Declare a variable / property outside the promise chain, then assign it the value when the promise is resolved. Generally, something like

api.posts
  .browse({ limit: 5, include: 'tags,authors' })
  .then(response => vm.data.posts = response)

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