首页 > 解决方案 > 在 for 循环中处理返回承诺结果

问题描述

我是 JS 和 Vue 的新手。

我有 100 行 url 发送到后端。我使用 for 循环调用 api,数据是每一行。

 <template>
    <table>
      <thead>
          <tr>
             <th>No.</th>
             <th>Url</th>
             <th>Status</th>
         </tr>
      </thead>
      <tbody>
          <tr v-for="(post, index) in posts">
             <td>{{ index + 1}}</td>
             <td>{{ post.url}}</td>
             <td class="classStatus(post.status)">{{ post.status}}</td>
          </tr>
      </tbody>
    </table>

脚本:

const apiUrl = 'example.com/api/createPost'

 for (post of this.posts) {
    // Sent only posts with status READY or FAIL
    if (post.status === STATUS_SUCCESS) {
        continue;
    }
    
    // Call api to process post one by one
    this.apiService(apiUrl, post)
        .then(result => {

             post.status = STATUS_SUCCESS
         }).catch(err => {

             post.status = STATUS_FAIL
         })
}

它适用于单个帖子(api 调用 1 次):

但是,如果有多个帖子:

你能帮我知道为什么会有多个帖子发生吗?

标签: javascriptrestvue.jserror-handlinges6-promise

解决方案


推荐阅读