Home > Mobile >  How to execute promise call sequentially for fetch api
How to execute promise call sequentially for fetch api

Time:10-31

I have to call fetch api till it's response value is updated(response value will get updated only after a time period). let p1 = fetch(url); How to call to this fetch api by executing multiple promise sequentially till the response value is updated

I tried to achieve the same using infinite loop. But that did not work. How to achieve this using promise?

CodePudding user response:

You can use async and await:

(async function () { 
     while (true) {
         let p1 = await fetch(url);
         // Make your check on the response. For example:
         let obj = await p1.json();
         if (obj.someField == someValue) return something;
     }
})(); // Call the async function immediately

CodePudding user response:

@trincot nailed it with his answer. Here is a demo of his approach (I cheated a little bit: as my AJAX endpoint returns only static data I changed the request each time as url i):

const url="https://jsonplaceholder.typicode.com/users/";
(async function () { 
  for(let i=1;i<100;i  ) { // limited to 99 tries...
   let obj = await fetch(url i).then(r=>r.json());
   console.log(obj.name);
   if (obj.name.toLowerCase().includes("kurtis")) return obj;
  }
})().then(res=>{
  // to be executed after the object was found and returned in RES:
  console.log("the result is:",res);
});

Instead of while I used a for loop. This gives me an easy way of limiting the maximum number of tries (here: 99).

  • Related