0

I have used the async function and waiting for one API to hit and display its current file name which got uploaded then increase the counter I and go for the next file.

ISSUE: The async and await is working fine but the callbacks are called after all the requests have been made.

How can I hit the API and get its name printed then go for another file to hit the API?

PS: I can't change callback to promise, it's a defined structure in my organization as of now.

Code:

uploadCallback = () => {
  console.log(currentFile)
}

const loop = async() => {
  for (let i = 0; i < this.state.fln.length; i++) {
    currentFile = obj.fln;
    await uploadAPI(obj, this.uploadCallback);
    console.log('currentFile:', i, currentFile);
  }
};
Rahman Haroon
  • 1,088
  • 2
  • 12
  • 36
Ayushi Keshri
  • 680
  • 7
  • 18

2 Answers2

0

You could try something like this:

uploadCallback = () => {
  console.log(currentFile)
}

const loop = async() => {
  for (let i = 0; i < this.state.fln.length; i++) {
    currentFile = obj.fln;
    const res = await uploadAPI(obj);
    this.uploadCallback(res);
    console.log('currentFile:', i, currentFile);
  }
};

This will make sure that the callback is called only after uploadAPI finishes.

Shriharsha KL
  • 317
  • 1
  • 2
  • 11
0

You'll need to integrate promises. Here's an example with the Pokemon API...

 let thisstateflnlength = 5
    
    const getAPI = (counter = 0) => {
      if (counter <= thisstateflnlength) {
        fetch("https://pokeapi.co/api/v2/pokemon/ditto").then(response => response.json()).then(data =>{
          console.log(data.forms[0])
          console.log(counter)
        }).then(data => getAPI(counter+1))
    
      }
    }
    
    getAPI()

The counter logs from 0-5 and each API call is executed asynchronously.

Paul Martin
  • 451
  • 2
  • 7