how to stop looping when json is empty?

I have an API and it has pagination. but in jsonnya there is no total page data. so I made a script to get the page count. the script is like this

$(document).ready(function () {
            for (let i = 0; i < 10000; i++) {
                console.log(i + 1)
                hst = window.location.origin
                row = i + 1
                rl = hst + "/admin/all?page=" + row + "&limit=15"
                fetch(rl)
                    .then(res => res.json())
                    .then(data => {
                        // console.log(data.user_data)
                        if (i == 2) {
                            return
                        }
                    })
            }
        })

json

{
  "limit": 1,
  "page": 3,
  "user_data": [
    {
      "ID": 5,
      "CreatedAt": "2021-03-04T17:07:08+07:00",
      "UpdatedAt": "2021-03-04T17:07:08+07:00",
      "DeletedAt": null,
      "Email": "asdasd",
      "Password": "asdas",
      "Name": "asd",
      "UserRoleID": 1,
      "UserRole": {
        "ID": 1,
        "Name": "Admin"
      }
    }
  ]
}

then how to stop the for looping when the json “user data” is empty? like this

{
  "limit": 1,
  "page": 4,
  "user_data": [
    
  ]
}
``

Answer

It seems that you misunderstood the promise part of your code.

If you want to write it like that, you must use async/await syntax :

$(document).ready(async function () { //THERE
            for (let i = 0; i < 10000; i++) {
                console.log(i + 1)
                hst = window.location.origin
                row = i + 1
                rl = hst + "/admin/all?page=" + row + "&limit=15"
                const resp = await fetch(rl); //we send the request
                const json = await resp.json(); //we get the response body as JSON
                if(json.user_data.length === 0) break;
                //json contains all your json content
          
            }
        })
   }

Why ?

Because promises are asynchronus. When they will resolve, your forloop will be over for ages (at computer scale). Promise.then() will never block your thread and continue the execution.

So, if you loop on 10 elements, you will send 10 simultaneous request that will (or will not) resolve in some order (likely not the one you think) later.

There is more info about promises there, if you want : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Async/await

The async/await syntax is syntactic sugar : under the hood, you get Promises, but the syntax allow you to write your code in a way that looks synchronus. It’s far easier to read AND to write, but you can do the same thing.

If we get your example again, you could write it like this (to get ride of async/await and use pure Promise syntaxe ) :

let row = 0;
function fetchThings(){
   if(row >= 10000) return;
   hst = window.location.origin
   row = i + 1
   rl = hst + "/admin/all?page=" + row + "&limit=15"
   fetch(rl).then(resp=>resp.json()).then((json)=>{
       if(json.user_data.length > 0) fetchThings();
   })
}

$(document).ready(fetchThings);
 

Leave a Reply

Your email address will not be published. Required fields are marked *