Introduction: Utilizing TypeScript and node-pg (Postgres for Node), I am populating an array of promises and then executing them all using Promise.all()
.
While pushing queries into an array during iteration over a set of numbers, an error occurs when the loop is structured like this:
const gameIds = [1,2,3,4,5];
let queryArray = [];
const sql = 'select bettor, fader from wagers where game_id=$1';
gameIds.forEach((gameId: number)=> {
// populate the query array
queryArray.push(DatabaseOperations.dbConnection.query(sql, [gameId]));
});
let allWagersForGames = await Promise.all(queryArray);
The error arises when trying to assign the results of the promise array to allWagersForGames
, presenting the message:
Variable 'queryArray' implicitly has an 'any[]' type.ts(7005)
.
However, iterating over the number array in the following way eliminates errors without clear reasoning why a change in iteration style influences the occurrence of the previous error:
const gameIds = [1,2,3,4,5];
const sql = 'select bettor, fader from wagers where game_id=$1';
for (const gameId of gameIds) {
// populate the query array
queryArray.push(DatabaseOperations.dbConnection.query(sql, [gameId]));
}
// retrieve all of the data now
let allWagersForGames = (await Promise.all(queryArray));