在for循环中处理返回承诺结果

时间:2020-07-11 07:35:11

标签: javascript rest vue.js error-handling es6-promise

我是JS和Vue的新手。

我有100行发送到后端的网址。我使用了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次):

  • 1个有效网址(插入后端)-> post.status更新为STATUS_SUCCESS
  • 1个无效的url(后端控制台中引发异常)-> post.status已更新为STATUS_FAIL

但是,如果有多个帖子:

  • 无效的URL 之前有效 =>两行post.status已更新为FAIL
  • 有效的url无效之前 =>状态已正确更新,但我仅检查了网络调用API一次。

您能帮我知道为什么发生了多个帖子吗?

  • 我不知道为什么如果在有效数据之前调用了无效数据,它们都将失败?
  • 我的脚本是反模式吗? (在循环内调用API)

0 个答案:

没有答案