Added `AsyncIterator`
Added the AsyncIterator
class to support the (somewhat) new [Symbol.asyncIterator]
protocol. This new class allows for iteration over an array of Promises using the for await
syntax:
async function fetchWeatherForCity(city: string): Promise<WeatherData> { ... }
let weatherAsyncIterable: AsyncIterable<WeatherData> = new AsyncIterable([
fetchWeatherForCity("Chicago"),
fetchWeatherForCity("New York"),
fetchWeatherForCity("Seattle"),
fetchWeatherForCity("Miami")
]);
for await (weatherData of weatherAsyncIterable) {
console.log(`${weatherData.location}: ${weatherData.temperature}`);
}
The above code would print out the temperature in each city, as the data becomes available. This is to say that if whatever API we are using to get weather data responds with data for Seattle in 500ms, but then takes 4 seconds to return us data for Chicago, the Seattle data will be printed as soon as it becomes available, and the same goes for the Chicago data.
The above code is akin to doing something like the following:
async function fetchWeatherForCity(city: string): Promise<WeatherData> { ... }
let weatherDataPromises: Promise<any>[] = [
fetchWeatherForCity("Chicago"),
fetchWeatherForCity("New York"),
fetchWeatherForCity("Seattle"),
fetchWeatherForCity("Miami")
];
weatherDataPromises.forEach((weatherDataPromise: Promise<WeatherData>): void => {
console.log(`${weatherData.location}: ${weatherData.temperature}`);
});
await Promise.all(weatherDataPromises);
But who doesn't like using new shiny syntax? 😄