Ways to retrieve the output of a generator

event.ts

export interface Action {
    description: string;
    location: string;
    duration: number;
}

export interface IEvent {
    title: string;

    actions: Array<Action>;
}

Festival.ts

import {IEvent, Action} from './interfaces/event'

export default class Festival implements IEvent {
    title: string = 'Adventure at the festival';

    actions: Array<Action> = [
        {
            description: 'You arrived at the festival',
            location: 'https://example.com/festival.jpg',
            duration: 3000,
        },
        {
            description: 'You see a stage in front of you',
            location: '',
            duration: 5000,
        },
    ];

    private *listActions(actions: Array<Action>): IterableIterator<Action> {
        yield action;
    }   

    start(): void {
        for (const action of this.listActions(this.actions)) {
            setTimeout(() => {
                console.log(action.description);
                action.next();
              }, action.duration);
        }
    }
}

I am trying to move to the next action after a certain time but encountering an error:

The property 'next' is not present on the type 'Action'.

There is also an issue with the absence of `action` for some reason, and I'm unsure why.

Answer №1

A different approach would be more suitable in this scenario to achieve the desired outcome without using generators. Consider implementing either a callback-based solution or utilizing promises with async/await:

start(callback?: () => void): void {
    this.steps.reduceRight((next, step) => () => {
        console.log(step.text);
        setTimeout(next, step.time);
    }, () => {
        console.log('All steps done');
        callback?.();
    })();
}

or with promises and async/await:

async start(): Promise<void> {
    for (const step of this.steps) {
        console.log(step.text);
        await new Promise(resolve => setTimeout(resolve, step.time));
    }
    console.log('All steps done');
}

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

The method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not provide any output

After running all JavaScript, I need to retrieve the HTML content. However, I am facing an issue using WebKit.NET where the method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not return anything, even with a simple alert(). When I try passi ...

Using Vue with Axios allows for making a GET request with a variable that is obtained from a separate GET request

After successfully building a component that showcases 3D print information, known as a fabmoment, I managed to populate an author-object and a fabmoment-object with data using the $route.params. Here's how: <script> import SingleSummarized fro ...

The issue with mongodb .deny() function in Meteor: Troubleshooting the problem

Here is the code snippet: Cashier.deny({ insert() { return true; }, update() { return true; }, remove() { return true; }, }); It seems that this code is not functioning as expected. I have attempted to update data from the client using Mongol, but ...

Managing errors through middleware functions

Currently, I've been studying node.js on and off. I came across this question: Middleware 1: app.use(function(req, res, next) { db.load(function(err, session) { if (err) { return next(err); } ... }); }); Middleware 2: app.u ...

Adding a backslash in Angular: Tips and Tricks

I have a question about adding a backslash to a string that is returned from a div, for example Car1 \sold. Although I am able to retrieve the status, I am having trouble adding the backslash. Here is what I have tried so far: <span>{{addBackl ...

Enhancing the aesthetic appeal of Angular2 Google Maps

Hey there, I'm a newcomer to Angular2/Typescript and I've been working on styling a map in my Angular2 project. I integrated a map using the Angular2 Google Maps Components, but I'm having trouble with applying styles through the undocumente ...

Bringing a .json Model into Three.js

Exploring Three.js for the first time and struggling with importing a .json model obtained from Clara.io For instance, I have downloaded this model: However, I can't seem to understand how to embed it into an HTML file. :( I attempted the following ...

Struggling to synchronize animation timing between elements using jquery

When you navigate to an album (for example, Nature because I'm still working on the others) and select one of the images, they all gradually fade out while the selected image appears on the screen. What's actually happening is that the selected i ...

Issue: The child component is not being displayed in a nested route in React

Utilize React nested routes with Home as the parent and News as the child. The directory structure consists of a "src" folder at the root containing a "pages" folder which further contains "Home" and "News" folders. Inside the "News" folder, there is an in ...

Tips for rendering only the descending portion of a spline in three.js

In three.js, I have the ability to draw a spline using three coordinates - start, mid, and end. When creating this spline, the curve starts at the 'start' coordinates, rises to the 'mid' position, and then falls to the 'end' c ...

Rendering on the server without using any client-side JavaScript

As I work on developing an application that can handle data submission through both ajax and traditional form requests, I am surprised by the lack of resources available online on this topic. It seems like we now generally assume client-side JS is readily ...

Error: The function _this[("render" + data.type)] is not defined as a valid function

https://i.stack.imgur.com/Y5Dz5.jpg I encountered an error in the console that I can't seem to figure out. Despite following the Syncfusion library's documentation, the error persists. Here is the code snippet that I implemented: import React f ...

The PHP counter conceals the comma upon loading and does not display it permanently

I'm currently working on a PHP counter and encountering an issue with the comma display. I have implemented Number Format in a PHP function to print counter digits with commas every 3 digits, but the comma doesn't remain visible after the page lo ...

Integrating DHTMLX Scheduler with Node JS for seamless scheduling solutions

Having diligently followed the DTHMLX Scheduler guide, I've encountered an issue with the db.event.insert() function not working, as the associated route fails to trigger. Interestingly, data from my MongoDB displays correctly when inserted via the sh ...

The 'async' keyword is not permitted in this context within a TypeScript React application

An issue has arisen with the aync, indicating that the async modifier is not permitted in this context: private async getValue= (acc: Access): void => { await this.service.getForm(''); } It appears that there might be an ...

Concerns with the performance of Leaflet's polyline

Currently using Leaflet version 1.0.3 and encountering an issue with GPS positions on my map. Within a for loop, I am creating circle markers for each GPS position: var position = new L.latLng(lat, lng); coordinates.push(position); L.circle([lat, lng], ...

Having difficulty storing duplicate requests that are crucial for various services/components

Currently, I am tackling a project that involves displaying multiple sets of data to the user. Each set requires several requests to be made to the backend. Specifically, for the UserDetails dataset, I must query the getUser and getSigns endpoints. However ...

Adding individual flag icons for each country in your Datatables can be a significant enhancement to

Below is the code snippet in JavaScript with flags: <script type="text/javascript"> $(document).ready(function() { var dataTable = $("#example").DataTable( { processing: true, bSort: false, ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Could someone clarify for me why I am unable to view the connection status within this code?

Having trouble with the Ionic Network plugin. I've included this code snippet, but it's not functioning as expected. No console logs or error messages are showing up. import { Network } from '@ionic-native/network'; ionViewDidLoad() { ...