Error: Typescript foreach loop encountering 'Expression yields void type'

Currently, I am working on setting up a cron job to monitor the completion of my tournaments and trigger some specific code upon completion. For reference, I came across this example:

During deployment of my code, an error popped up as follows:

ERROR: functions/src/index.ts:23:9 - Expression has type `void`. Put it on its own line as a statement.

Below is the taskRunner function that I've been using:

export const taskRunner = functions.runWith( { memory: '2GB' })
    .pubsub
    .schedule('* * * * *').onRun(async context => {

        // Consistent timestamp
        const now = admin.firestore.Timestamp.now();

        // Query all documents ready to perform
        const query = db.collection('tournaments').where('endDate', '<=', now).where('winnerUserId', '==', null); 
        const tournaments = await query.get();

        // Tasks to execute concurrently.
        const tasks: Promise<any>[] = [];

        // Loop over documents and push task.
        tournaments.forEach(snapshot => { // <-- error occurs on this line
            const { tournamentId, name } = snapshot.data();

            const task = completeTournament(tournamentId)
                .then(() => console.log("cron job", "Tournament '" + name + "' (id: " + tournamentId + ") completed successfully."));
                .catch((err) => console.log("cron job", "Tournament '" + name + "' (id: " + tournamentId + ") encountered an error: " + err));

            tasks.push(task);
        });

        // Execute all jobs concurrently
        return await Promise.all(tasks);

});

The completeTournament() function can be found further in the file:

function completeTournament(tournamentId: string) {
    // Get the top entry user id
    db.collection("tournaments").doc(tournamentId).get()
        .then(tournamentDoc => {
            const winnerUserId = tournamentDoc.get("rank[0].userId")

            db.collection("tournaments")
                .doc(tournamentId)
                .update({ "winnerUserId": winnerUserId })
                .catch(err => {
                    console.log("Error completing tournament '" + tournamentId, err);
                });
        })
        .catch(err => {
            console.log("Error retrieving tournament '" + tournamentId, err);
        });
}

I'm relatively new to Typescript and suspect that I might be misusing function pointers. Any assistance on this matter would be highly appreciated. Thank you in advance.

Answer №1

Just a heads up for anyone who may encounter the same issue down the road:

After some feedback on my original post, I identified that the root of the problem lied within the .then().catch() calls within the completeTournament() function in the taskRunner. Instead of utilizing those calls there, I made the decision to rely on the .then().catch() within the actual task functions themselves.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Configuring Typescript target and library to utilize Promise.allSettled on outdated web browsers

I am currently using TypeScript version 4.3.5 and Node.js version 14.18.1 in my project. The code I am working on is compiled to target both old and new browsers by setting target=es5 in the tsconfig file. I make use of both Promise.all and Promise.allSett ...

Easiest Angular Carousel Solution

My goal is to create a basic Angular Carousel to enhance my understanding of Angular. While I have received helpful answers in the past, I am seeking further clarification to deepen my knowledge of Angular2+ and Typescript. Here's what I have so far: ...

Inheriting an Angular 5 class with injected dependencies

I recently defined a new class @Injectable FooService { constructor(private _bar:BarService){ } } Then I decided to extend it in the following way @Injectable ExtFooService extends FooService { constructor(private _bar:BarService){ ...

Rxjs: Making recursive HTTP requests with a condition-based approach

To obtain a list of records, I use the following command to retrieve a set number of records. For example, in the code snippet below, it fetches 100 records by passing the pageIndex value and increasing it with each request to get the next 100 records: thi ...

Leveraging Shared Modules Component across multiple modules in Angular can enhance code re

In my project structure, I have a shared folder containing shared.module.ts. Additionally, there is a modules folder with sub-modules, one of which is Dashboard.module.ts. Inside the shared module, I created a custom sidebar menu that I intend to use withi ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

What could be the reason for mocha failing to function properly in a project that is set up

During a unit test in my TypeScript project using mocha, I encountered an issue when setting the project type to module. The error message displayed is as follows: ➜ typescript-project yarn test yarn run v1.22.17 warning package.json: No license field $ ...

Issue in VueJs where mutations do not properly save new objects to the state

I am facing an issue with updating my vuex store after modifying my user credentials in a component. Below is the code snippet for reference: mutations: { updateUserState: function(state, user) { state.user = user; }, } actions: { updat ...

The method beforeEach in angular2/testing seems to be failing as it is not

Currently, I am utilizing Gulp, Gulp-Jasmine, and SystemJS to conduct tests on an Angular2 demo application. The setup is fairly straightforward. I have successfully implemented a System.config block and loaded the spec file. However, I encounter an error ...

Tips for transferring data from a service to a method within a component

I have a service that successfully shares data between 2 components. However, I now need to trigger a method in component A when an event occurs on the service (and pass a value to that component). Can someone guide me on how to achieve this? I have seen ...

Learn how to restrict input to only specific characters in an input box using Angular2 and validations

Is it possible to restrict user input in an input box to only specific characters such as '7' and '8'? I tried adding validations with attributes like type="number", min="7" and max="8", but even then other keys can be inserted before v ...

Sending the id from a component to a service in Angular

In my current project, I am working on a chat application using Angular with WebSocket integration. Let me provide an overview of the architecture I have designed for this project. I created a module called 'chatting' which contains a list of use ...

Deactivating Bootstrap Modal in Angular

Looking for advice on managing a Bootstrap Modal in Angular 7 I have a Form inside a Bootstrap Modal that I need to reset when the modal is closed (by clicking outside of it). Despite searching on Google, I haven't been able to find a solution. Any ...

Having trouble with updating a Firebase database object using snap.val()

I'm trying to figure out how to update a property within the snap.val() in order to make changes to my Firebase database. function updateListItem(listItem) { var dbRef = firebase.database() .ref() .child('userdb') .child($sco ...

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...

The W3C Validator has found a discrepancy in the index.html file, specifically at the app-root location

While attempting to validate my HTML page, I encountered the following error: Error: Element app-root not allowed as child of element body in this context. (Suppressing further errors from this subtree.) From line 4347, column 7; to line 4347, column 16 ...

Should an HTML canvas in Angular be classified as a Component or a Service?

I have a basic drawing application that uses an MVC framework in TypeScript, and I am looking to migrate it to Angular. The current setup includes a Model for data handling, a View for rendering shapes on the canvas, and a Controller to manage interactio ...

Utilizing Arrow Functions with Parameters in Angular

I am currently working on an Angular 4 app and I am attempting to create a queue of actions. Each action should only be executed after the previous one has finished, and each action should receive its own set of parameters. public activeRegistrationAndS ...

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...