or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mditeration.md

iteration.mddocs/

0

# Event Iteration

1

2

Async iteration functionality for continuous event stream processing with automatic cleanup and limit controls.

3

4

This document uses types defined in the main [p-event documentation](./index.md#base-types-and-interfaces).

5

6

## Capabilities

7

8

### Event Iterator Creation

9

10

Creates an async iterator that yields event values as they are emitted.

11

12

```typescript { .api }

13

/**

14

* Creates an async iterator for event streams

15

* @param emitter - Event emitter object

16

* @param event - Event name(s) to listen for

17

* @param options - Iterator configuration options

18

* @returns AsyncIterableIterator that yields event values

19

*/

20

function pEventIterator<EventName extends string | symbol, EmittedType extends unknown[]>(

21

emitter: Emitter<EventName, EmittedType>,

22

event: string | symbol | ReadonlyArray<string | symbol>,

23

options: IteratorMultiArgumentsOptions<EmittedType>

24

): AsyncIterableIterator<EmittedType>;

25

26

function pEventIterator<EventName extends string | symbol, EmittedType>(

27

emitter: Emitter<EventName, [EmittedType]>,

28

event: string | symbol | ReadonlyArray<string | symbol>,

29

filter: FilterFunction<EmittedType>

30

): AsyncIterableIterator<EmittedType>;

31

32

function pEventIterator<EventName extends string | symbol, EmittedType>(

33

emitter: Emitter<EventName, [EmittedType]>,

34

event: string | symbol | ReadonlyArray<string | symbol>,

35

options?: IteratorOptions<EmittedType>

36

): AsyncIterableIterator<EmittedType>;

37

38

type IteratorOptions<EmittedType extends unknown | unknown[]> = {

39

/** Maximum number of events before iterator ends @default Infinity */

40

readonly limit?: number;

41

/** Events that will end the iterator @default [] */

42

readonly resolutionEvents?: ReadonlyArray<string | symbol>;

43

} & Options<EmittedType>;

44

45

type IteratorMultiArgumentsOptions<EmittedType extends unknown[]> = {

46

multiArgs: true;

47

} & IteratorOptions<EmittedType>;

48

```

49

50

**Usage Examples:**

51

52

```javascript

53

import { pEventIterator } from 'p-event';

54

55

// Basic iteration

56

const iterator = pEventIterator(emitter, 'data');

57

for await (const data of iterator) {

58

console.log('Received:', data);

59

60

// Break condition

61

if (data.complete) break;

62

}

63

64

// With limit

65

const limitedIterator = pEventIterator(emitter, 'message', { limit: 10 });

66

for await (const message of limitedIterator) {

67

console.log('Message:', message);

68

}

69

// Automatically stops after 10 messages

70

71

// With resolution events

72

const iterator = pEventIterator(emitter, 'data', {

73

resolutionEvents: ['end', 'close']

74

});

75

for await (const data of iterator) {

76

console.log('Data:', data);

77

}

78

// Stops when 'end' or 'close' events are emitted

79

```

80

81

### Iterator Control Methods

82

83

The async iterator provides standard iterator methods for control flow.

84

85

```typescript { .api }

86

interface AsyncIterableIterator<T> {

87

/** Get next value from the iterator */

88

next(): Promise<IteratorResult<T>>;

89

/** Manually end the iterator and return a value */

90

return(value?: T): Promise<IteratorResult<T>>;

91

/** Make the object iterable in for-await loops */

92

[Symbol.asyncIterator](): AsyncIterableIterator<T>;

93

}

94

95

interface IteratorResult<T> {

96

done: boolean;

97

value: T | undefined;

98

}

99

```

100

101

**Manual Iterator Control:**

102

103

```javascript

104

import { pEventIterator } from 'p-event';

105

106

const iterator = pEventIterator(emitter, 'data');

107

108

// Manual iteration

109

while (true) {

110

const { done, value } = await iterator.next();

111

112

if (done) {

113

console.log('Iterator finished');

114

break;

115

}

116

117

console.log('Received value:', value);

118

119

// Manual termination

120

if (value.shouldStop) {

121

await iterator.return('stopped');

122

break;

123

}

124

}

125

```

126

127

### Advanced Iterator Patterns

128

129

Complex event processing patterns using iterator options and controls.

130

131

**Backpressure Handling:**

132

133

```javascript

134

// Iterator handles backpressure by queuing events

135

const iterator = pEventIterator(emitter, 'data');

136

137

// Emit events faster than processing

138

emitter.emit('data', 'value1');

139

emitter.emit('data', 'value2');

140

emitter.emit('data', 'value3');

141

142

// Values are queued and retrieved in order

143

console.log(await iterator.next()); // { done: false, value: 'value1' }

144

console.log(await iterator.next()); // { done: false, value: 'value2' }

145

console.log(await iterator.next()); // { done: false, value: 'value3' }

146

```

147

148

**Multiple Event Names:**

149

150

```javascript

151

// Listen to multiple events

152

const iterator = pEventIterator(emitter, ['data', 'message', 'info']);

153

154

for await (const value of iterator) {

155

// Receives values from any of the specified events

156

console.log('Event value:', value);

157

}

158

```

159

160

**Filter with Multi-Arguments:**

161

162

```javascript

163

// Complex filtering with multiple arguments

164

const iterator = pEventIterator(emitter, 'complex', {

165

multiArgs: true,

166

filter: ([type, data, metadata]) => {

167

return type === 'important' && data.priority > 5;

168

}

169

});

170

171

for await (const [type, data, metadata] of iterator) {

172

console.log('Important event:', { type, data, metadata });

173

}

174

```

175

176

**Zero Limit Iterator:**

177

178

```javascript

179

// Iterator with limit 0 immediately ends

180

const iterator = pEventIterator(emitter, 'data', { limit: 0 });

181

182

const result = await iterator.next();

183

console.log(result); // { done: true, value: undefined }

184

```

185

186

### Error Handling in Iterators

187

188

Event-based error handling within iterator loops.

189

190

```javascript

191

import { pEventIterator } from 'p-event';

192

193

try {

194

const iterator = pEventIterator(emitter, 'data', {

195

rejectionEvents: ['error'],

196

timeout: 5000

197

});

198

199

for await (const data of iterator) {

200

console.log('Processing:', data);

201

}

202

} catch (error) {

203

if (error instanceof TimeoutError) {

204

console.log('Iterator timed out');

205

} else {

206

console.log('Iterator error:', error);

207

}

208

}

209

```

210

211

### AbortSignal Integration

212

213

Integration with standard Web API cancellation patterns.

214

215

```javascript

216

// Using AbortController for cancellation

217

const controller = new AbortController();

218

219

setTimeout(() => {

220

controller.abort('timeout');

221

}, 10000);

222

223

try {

224

const iterator = pEventIterator(emitter, 'data', {

225

signal: controller.signal

226

});

227

228

for await (const data of iterator) {

229

console.log('Data:', data);

230

}

231

} catch (error) {

232

console.log('Aborted:', error.message); // 'timeout'

233

}

234

```