Skip to content
Advertisement

Async Loop Not Honoring Async

I have been a bit stuck on an Async function.

What I am trying to accomplish – I am creating a batchProcessing function (batchGetSubs) which will loop through a set of files, read a ID, then make an API request, wait for a response (THE ISSUE) and then to write to a new file with the formatted data.

The issue – I have tried both Async and Await, as well as pushing promises and trying to use a Promise.all to wait for promises to be resolved, but with no success. Current behavior is that I get all of my console.logs that are in the Promise.all section before the API calls actually return all the data. I have used these articles as reference:

The Code

JavaScript

Advertisement

Answer

I only checked the first function, where you had put your question:

WHY IS THIS NOT WAITING FOR ALL RESPONSES?

For several reasons:

  1. The promise array is still empty when you call Promise.all. This is because you only do a push after an await, and so that push happens asynchronously (read: later).

  2. Even when the promises array gets populated, it will not have promises objects, but resolved values (i.e. newRecord values)

  3. Even if promises would have been array of promises, you don’t pass that array correctly to Promise.all: you wrap that array in yet another array, which then only has one entry, and that entry is not a promise, but an array.

Not related to your problem, but:

  • please make it a habit to explicitly declare all your variables. You did not do this for iteration, promises, nor i.

  • Only use .map when you do something with the return value. For pure iteration use .forEach or for. In this case, you can use the return value to extend the promises array.

  • If you intend to call batchGetSubs and need to know when all is done, then make sure it returns a useful promise: return Promise.all()

Here is the suggested correction for that function:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement