Error encountered when asynchronously iterating over an object in TypeScript

Could someone please help me understand why I am getting an error with this code?

var promise = new Promise((resolve, reject) => {
    resolve([1, 2, 3, 4, 5]);
});

async function doSomethingAsync() {
    var data = await promise;
    data.forEach(v => console.log(v));
}

doSomethingAsync();

When attempting to compile this using tsc file.ts --target ES6, I encounter the following issue:

error:async.ts(7,10): error TS2339: Property 'forEach' does not exist on type '{}'.

Answer №1

Finally cracked the code! We can easily enhance our Promise by adding a generic type:

'use strict';

var promise = new Promise<any[]>((resolve, reject) => {
    resolve(["gdfgdfgdf", "dfggfd", 1, 2, {}]);
});

async function doSomethingAsync() {
    let data = await promise;

    for (let i of data) {
        console.log(i);
    }
}

doSomethingAsync();

Now everything is working flawlessly without any coding confusion :)

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

Make sure to use jQuery waterfall 'reflow' only once all the images have finished loading

Currently, I am utilizing jQuery waterfall to achieve a grid-style display on my website. To address the issue of images overlapping, I have enclosed the waterfall method within a .load() function like this: $(window).load(function(){ $('#buildcon ...

Decorator used in identifying the superclass in Typescript

I am working with an abstract class that looks like this export abstract class Foo { public f1() { } } and I have two classes that extend the base class export class Boo extends Foo { } export class Moo extends Foo { } Recently, I created a custom ...

Error when parsing JSON due to the presence of backslashes within the serialized object

When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The respons ...

Execute javascript code 1.6 seconds following the most recent key release

Is there a more efficient way to execute JS 1.6 after a keyup event, considering that the timer should reset if another keyup event occurs within 1.6 seconds? One possible approach could involve utilizing a flag variable like this: var waiting = false; $ ...

Can you explain the meaning of this AJAX code snippet?

I've been researching online for information, but I'm struggling to find any details about the AJAX code snippet that I'm using: function getEmployeeFilterOptions(){ var opts = []; $checkboxes.each(function(){ if(this.checke ...

Preventing Vue.js SPA from accessing cached version when JWT expires: the solution

I'm encountering an issue with my Vue.js / Express application that I can't seem to resolve. Here's how the process unfolds: An unauthenticated user logs into the app and is presented with the login page. Once successfully authenticated, t ...

Is there a way for me to retrieve data from a v-for loop in VueJS with the Quasar Framework?

I am currently working on a q-markup-table code to display products based on a search query. I have successfully implemented a button that allows the user to select a row from the table, and once selected, the row data is sent to an array named "selected ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

how can I transfer model values to a dashboard in Rails 5?

I have developed an app that includes an adminlte dashboard. The dashboard is populated with various values obtained by a jQuery file. I am trying to pass module values to the dashboard. For example, the number of users shown in the dashboard should be fet ...

The 'GoogleAuthProvider' property cannot be found on the 'AngularFireAuth' type

When attempting to sign in with Google using 'AngularFireAuth', I encountered an error. Here is the code snippet from my auth.service.ts file: import { Injectable } from '@angular/core'; import { first } from 'rxjs/operators'; ...

Invoke the REST API and save the compressed file onto the local machine

This is the code snippet I currently have: jQuery.ajax({ type: "GET", url: "http://localhost:8081/myservicethatcontainsazipfile", contentType:'application/zip', success: function (response) { console.log("Successful ...

Repairing the Left-sided Popup Leaflet

Can someone help me with fixing the positioning of the Popup to the left of the map? Currently, it does not stay aligned to the left edge when moving the map. I tried using position: fixed in my styling, and while everything looks good when zooming, it br ...

Could the autofill feature in Chrome be turned off specifically for Angular form fields?

Even after attempting to prevent autofill with autocomplete=false and autocomplete=off, the Chrome autofill data persists. Is there a method to disable autofill in Angular forms specifically? Would greatly appreciate any recommendations. Thank you. ...

forwarding within afterCallback employing nextjs-auth0

I need to handle multiple cases for redirecting users based on various fields and custom claims in the user token, which involves navigating through complex if/else blocks. Let's consider a simpler example where I want to redirect the user to /email- ...

The Issue of Anti Forgery Token Not Functioning Properly with Ajax JSON.stringify Post

I have been attempting to utilize an Anti Forgery token with JSON.stringify, but despite researching multiple sources, I have not been successful. Below is my AJAX code for deleting some information without any issues. Upon adding the anti forgery token, I ...

Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call. <script type="text/javascript"> $(document).ready(function() { $('#call').click(function () { $.ajax({ type: "post", ...

Warning: The attribute 'EyeDropper' is not recognized within the context of 'Window & typeof globalThis'

Attempting to utilize "window.EyeDropper" in a project that combines vue2 and TypeScript. When writing the following code: console.log(window.EyeDropper); An error message is generated by my Vetur plugin: Property 'EyeDropper' does not exist on ...

The ng-include feature seems to be malfunctioning

After building a basic web page using AngularJs, I ran into an issue when attempting to integrate header.htm into index.html - nothing was displaying in the browser. index.html <html> <script src="https://ajax.googleapis.com/ajax/libs/angul ...

"I'm encountering an issue with Passport.js where req.isAuthenticated is throwing an error as not

Recently I started working with node and express, along with passport.js for building an authentication feature. However, I encountered an issue while using a middleware function called "checkNotAuthenticated" in my routes. The error message I received was ...

Utilizing JavaScript for the removal or hiding of span elements with specific class attributes

I am currently working on a software project that involves compiling HTML fragments and then exporting them to Microsoft Word. My goal is to create a script that will cycle through these compiled fragments and remove specific tags that have a particular CS ...