-1

When call the function below I am getting undefined for q. I do not know what to do. Please help. Thank you. I have tried passing q into then as a parameter but it does not work.

myfunction = () =>{
      
       sendFetch(
               `http://api.com`,
               GET
             ).then((response)=>{
              
               for (var i = 0; i < response.data.length; i++) {
                 processed_data.push(response.data[i].description);
               }
               
               for (var q = 0 ; q < array.length; q++)
               {
                sendFetch(
                  `api.com`,
                  GET
                ).then((response)=>{

                  
                console.log(q)
                 
                })

               }
              
               
             })
        
   } 
Daniel
  • 103
  • 1
  • 1
  • 6
  • No, `q` will not be undefined. It will have the value of `array.length` when it is logged. `array[q]` will be `undefined` though. – Bergi Jul 05 '22 at 22:34
  • Please provide a [mcve], including the full definition of `sendFetch`, that demonstrates the issue, if you need further help with this. – Bergi Jul 05 '22 at 22:36

2 Answers2

0

I suggest studying scopes and the difference between "var" and "let". Also async and promises.

We don't use "var"s anymore and be careful about declaring variables with equals name. You are using "response" in the same scope.

Femow
  • 1
-1

You can await the sendFetch instead of using then catch. Trye this:

myfunction = () => {

    sendFetch(
        `http://api.com`,
        GET
    ).then(async (response) => {
        for (var i = 0; i < response.data.length; i++) {
            processed_data.push(response.data[i].description);
        }

        for (var q = 0; q < array.length; q++) {
            try {
                const res = await sendFetch(
                    `api.com`,
                    GET
                )
                console.log(res)
                console.log(q)
            } catch (error) {
                console.log(error.message)
            }
        }
    }).catch(error => {
        console.log(error.message)
    })

}