1

I'm newbie in JS and Vue.

I have 100 rows of url that sent to Backend. I used a for loop to call api with data is each row.

 <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>

Script:

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
         })
}

It's work with cases single post (api call 1 time):

  • 1 valid url (inserted in backend) -> post.status updated to STATUS_SUCCESS
  • 1 invalid url (Throw exception in backend console) -> post.status updated to STATUS_FAIL

But, in cases multiple posts:

  • row invalid url before valid => both rows post.status updated to FAIL
  • row valid url before invalid => status updated correctly, but I check network call API just 1 time.

Can you help me to know why there are multiple posts happend?

  • I dont know why they both fail status if a invalid data called before the valid
  • Is my script was an Anti pattern? (call API inside loop)
Minh Quang
  • 21
  • 4
  • The problem is `for (post of this.posts)` which needs to be `for (let post of this.posts)`. Always use strict mode to catch accidentally global variables! – Bergi Jul 11 '20 at 16:52
  • "*Is an API call inside a loop an Anti pattern?*" - yes. It's much more efficient to do a single API call which will return all the results with only one HTTP request. Try to find (or create) and endpoint which does that for all the posts you need. The loop might be fine when you do it for 0-3 rows (where you don't know how many are shown), but it's a major performance issues for 100 rows. – Bergi Jul 11 '20 at 16:55
  • @Bergi: Thank you for your comment. But, I have problem with connection timeout. If i use 1 request for 100 data row, then the connection spend 100 seconds. It due to timeout error. So, I try to made 100 connection, each spend 1 second. Anyway, thank you for let me know that i used an anti pattern – Minh Quang Jul 12 '20 at 02:51
  • No, a properly built server should not need 100s to return 100 rows. What is the server doing? Can't it be parallelised? – Bergi Jul 12 '20 at 10:59

0 Answers0