Home > Software engineering >  while loop not waiting for await
while loop not waiting for await

Time:04-24

I know there's a ton of these questions but I haven't been able to find one that fits my case. I'm making api calls in a while loop and just don't want to time out my calls by rapid firing them. The while loop doesn't seem to be waiting for the call to finish.

while(it < array.length){
    await apiFunction(array[it]);
    console.log(it);
    it  
}

and the function

async apiFunction(array){
    try{
        (async () => {
            const result = await api.doStuff(array);
            console.dir(result);
        }
    } catch (e) {
        stuff;
    }
}

I've also tried adding a return(result) but that didn't change anything

My console output is

0
1
result
result

How can I get the while loop to wait until the api call is done? so my console looks like

0
result
1
result

CodePudding user response:

I had too many layers of asynchronicity going I guess. Just removed the async from inside the apiFunction

async apiFunction(array){
    try{
        const result = await api.doStuff(array);
        console.dir(result);
    } catch (e) {
        stuff;
    }
}

CodePudding user response:

Try to assign the result of a asynchronous function to a variable. If you do just

await apiFunction(array[it]);

This may prevent your promise from resolving.

Try

while(it < array.length){
const res = await apiFunction(array[it]);
console.log(it);
//return res
//console.log(res);
it   
}

Also try using other iterators, like for( of )

for (const element of array) {
const res = await apiFunction(element);
//return res
//console.log(res);
}

I haven't had any problems with it.

  • Related