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

What is the best way to shift focus to the next input field once the character limit has been reached, especially when the input is contained

My challenge lies in having six input fields arranged side by side in a single row: In my component.html file: onDigitInput(event: any) { let element; if (event.code !== 'Backspace') element = event.srcElement.nextElementSibling; consol ...

Working with Angular to add various items to an array based on multiple conditions

Currently, I am a beginner in TypeScript and currently involved in an Angular project. As part of my work, I need to make an API call and perform various operations on the received data: public data_Config: IConfig[] = []; this.getService.Data(input).sub ...

Dynamically change or reassign object types in TypeScript

Check out the example you can copy and test in TypeScript Playground: class GreetMessage { message: {}; constructor(msg: string) { let newTyping: { textMsg: string }; // reassign necessary this.message = newTyping; this.message.textMsg = msg; ...

Attempting to perform an API invocation on a distant endpoint utilizing NestJS

var unirest = require("unirest"); var req = unirest("GET", "https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data"); req.query({ "ingr": "1 large apple" }); req.headers({ &qu ...

Having trouble installing memlab using the npm package

Recently, I made an attempt to install the memlab library from Meta's GitHub. Initially, when I installed it without using the -g flag, the installation was successful. However, I encountered an issue where I could not execute any of the memlab comman ...

Using an array of functions in Typescript: A simple guide

The code below shows that onResizeWindowHandles is currently of type any, but it should be an array of functions: export default class PageLayoutManager { private $Window: JQuery<Window>; private onResizeWindowHandlers: any; constructor () { ...

The IDBCursor type does not have a property named 'value'

It appears that the typescript typings are not aware of the value property on the IDBCursor interface. let cursor: IDBCursor; cursor.value ...

In React + TypeScript, learn how to effectively pass down a function from a container component to a

I am currently working on developing a tabs application using React and Typescript. The main component, Tabs, manages the state and passes it down to the Content component. Additionally, I have implemented a function called 'handleName' which is ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

Is it feasible to restrict a generic type using typeguard?

I'm currently working on refining a generic function, where the autocomplete feature recognizes that it's encountering a typeguard, preventing it from revisiting the same code block. I suspect that the issue lies in not restricting the type to th ...

Translate array into object with correct data types (type-specific method)

Welcome In our project, we have implemented attributes support where each attribute acts as a class. These attributes include information on type, optionality, and name. Instead of creating an interface for every entity, my goal is to automate this proces ...

Tips for customizing the appearance of a label when a MUI Radio Button is selected

Hello everyone, I am attempting to customize the label text color of a radio button to turn blue when selected. https://i.stack.imgur.com/btSc2.jpg HERE IS THE CODE FOR MY MUI BUTTON SO FAR import * as React from "react"; import Radio from &quo ...

I am facing the issue of being unable to bind to 'routerlink' because it is not recognized as a known property of 'a', even after I have declared RouterModule in my app.module

Encountering a template parse error when using [routerlink] in an HTML page, despite importing RouterModule. Here's the relevant HTML snippet: <mat-toolbar color="primary"> <h3 [style.color]="white">ADMIN PORTAL</h3> <span cl ...

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

Typescript: Potential null object error when defining a method

I recently encountered an error message stating "Object is possibly null" while working on the changePageSize method in book-store.component.html. It seems like I need to initialize the object within the class, but I'm not familiar with how to do that ...

Display a dynamic array within an Angular2 view

I have a dynamic array that I need to display in the view of a component whenever items are added or removed from it. The array is displayed using the ngOnInit() method in my App Component (ts): import { Component, OnInit } from '@angular/core' ...

Is there a way to obtain a unique response in TestCafe RequestMock?

With Testcafe, I have the capability to simulate the response of a request successfully. I am interested in setting up a caching system for all GET/Ajax requests. The current setup functions properly when the URL is already cached, but it fails to prov ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...