Hi, I'm new to svelte. I was hoping this would work
<script>
export let name
function* reverse(text) {
for( let index = text.length -1; index > -1; index--) {
yield text[index]
}
}
$: eman = reverse(name)
</script>
<h1>Hello
{#each enam as char}
{char}
{/each}
</h1>
It doesn't seem to. I'm making the feature request that there be a way to handle iterators or streams in general. I know there is a special await syntax for promises, it would be great if there was such a thing for iterators. My search didn't find any such syntax.
Agreed, I was actually about to open an issue with the same suggestions yesterday. For what it's worth, I realized that it's usually easy to work around by spreading the iterator into an array:
<h1>Hello
{#each [...enam] as char}
{char}
{/each}
</h1>
I still think it would make a lot of sense for Svelte to support iterators better. Like @babakness says, Svelte embraces Promises with special syntax, rather than come up with its own convention for async values. It ought to do the same with iterators, as they are becoming the "expected" way to handle iteration in JS, but instead it just looks for a "length" property (which I believe isn't even documented).
You lose some of what's nice about iterators by spreading them ahead of time, as you can't manipulate the iteration as you go. For example, I wanted to yield an object with a callback and pass it to a child component, to allow it to influence the rest of the iteration.
Hey @trbrc, yes but that can't work on all iterators. An async iterator can run overtime, sort of like a stream or subscription. An async iterator can listen for click events on a dom element
Example:
https://itnext.io/understand-async-iterators-665259680044
Of course, but I鈥檓 not sure I understand your suggestion then. To my intuition your code snippet would be synchronous, outputting all of the characters at the same time.
Are you saying that you expected to be able to output the characters asynchronously, one at a time? What would drive the updates?
Looking at this again, I don't think we want to have a special syntax for iterating through iterables. You can just use a spread to turn it into an array, or implement something in a userland wrapper component if you want to be able to incrementally add iterations instead of adding them to the DOM all at once, or if you want to support async iterables.
I personally believe that being able to incrementally add iterations to the DOM using svelte should be a priority. Async iterator/generator is the cornerstone of modern web apps. It is frequently used to consume query result streams and deferring this to a wrapper component would be an anti-pattern.