For loop in TypeScript

Tram Ho

Introduce

I am new to the typescript language and have encountered some problems related to loops, so I share here so that the following friends have an overview of the loops in typescript, thereby saving A little time to find out. OK let’s start.

For

Traditional for style, like in other languages:

Here, the first expression is executed before the start of the loop. The second expression is the condition to execute the loop. And the third expression is executed after doing everything in the loop. Note that AFTER.

Then will print out:

For … of

However, typescript works very well with objects. So there are loops that are dedicated to objects. For..of is one such loop. This loop will iterate over the values ​​of the array, list, string, Object, … For example:

When used to traverse objects, for..of is often used in conjunction with Object.values ​​() – returns an array of values ​​and Object.keys () returns an array of keys for the object.

Normally, we will access the value by key using the [] operator.

For … in

Similar to for … of, but with object key.

Promise.all ()

Another way to iterate over the elements in an object is to use promise.all () in conjunction with the map () function to handle asynchronously.

The map () function will return an array of promises, our job is promise.all to wait for all the promises to be processed, too convenient, right.
Note that when 1 process in promise.all fails, all promises stop. This can affect the output. To avoid this, put try … catch in the handler function so that the process won’t be interrupted. The code will become:

summary

Above are some of my shares about loops in typescript. At the beginning, there are still many surprises, looking forward to everyone’s comments.
Happy coding ❤️

Share the news now

Source : Viblo