or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced.mdcollections.mdcore-promises.mdflow-control.mdfunctional.mdindex.mdnodejs.mdpromise-chains.mdproperty-access.mdqueue.mdstate-inspection.md

collections.mddocs/

0

# Collection and Array Operations

1

2

Functions for working with arrays of promises, combining multiple asynchronous operations, and processing collections of data.

3

4

## Capabilities

5

6

### All Operation

7

8

Combines multiple promises into a single promise that resolves when all input promises resolve.

9

10

```javascript { .api }

11

/**

12

* Turns array of promises into promise for array of values

13

* @param promises - Array of promises or values

14

* @returns Promise that resolves to array of all resolved values

15

*/

16

function Q.all(promises);

17

18

/**

19

* Instance version of Q.all for promise of array

20

* @returns Promise for array of resolved values

21

*/

22

promise.all();

23

```

24

25

**Usage Examples:**

26

27

```javascript

28

const Q = require("q");

29

30

// Static version with array of promises

31

const allPromise = Q.all([

32

Q.resolve(1),

33

Q.resolve(2),

34

Q.resolve(3)

35

]);

36

37

allPromise.then(values => {

38

console.log(values); // [1, 2, 3]

39

});

40

41

// Instance version with promise of array

42

const arrayPromise = Q.resolve([

43

fetchUser(1),

44

fetchUser(2),

45

fetchUser(3)

46

]);

47

48

arrayPromise.all().then(users => {

49

console.log("All users:", users);

50

});

51

52

// Mixed values and promises

53

Q.all([

54

"immediate value",

55

Q.delay("delayed", 100),

56

Promise.resolve("native promise")

57

]).then(results => {

58

console.log(results); // ["immediate value", "delayed", "native promise"]

59

});

60

```

61

62

### All Settled Operation

63

64

Returns a promise that resolves when all input promises settle (either resolve or reject).

65

66

```javascript { .api }

67

/**

68

* Returns promise for array of inspection states when all promises settle

69

* @param promises - Array of promises or values

70

* @returns Promise resolving to array of {state, value?, reason?} objects

71

*/

72

function Q.allSettled(promises);

73

74

/**

75

* Instance version of Q.allSettled for promise of array

76

* @returns Promise for array of settlement states

77

*/

78

promise.allSettled();

79

```

80

81

**Usage Examples:**

82

83

```javascript

84

const Q = require("q");

85

86

// Handle mix of successful and failed promises

87

const settledPromise = Q.allSettled([

88

Q.resolve("success"),

89

Q.reject(new Error("failure")),

90

Q.delay("delayed success", 100)

91

]);

92

93

settledPromise.then(results => {

94

results.forEach((result, index) => {

95

if (result.state === "fulfilled") {

96

console.log(`Promise ${index} succeeded:`, result.value);

97

} else {

98

console.log(`Promise ${index} failed:`, result.reason.message);

99

}

100

});

101

});

102

103

// Instance version

104

const arrayPromise = Q.resolve([

105

apiCall1(),

106

apiCall2(),

107

apiCall3()

108

]);

109

110

arrayPromise.allSettled().then(results => {

111

const successes = results.filter(r => r.state === "fulfilled");

112

const failures = results.filter(r => r.state === "rejected");

113

console.log(`${successes.length} succeeded, ${failures.length} failed`);

114

});

115

```

116

117

### Spread Operation

118

119

Spreads array values as individual arguments to callback functions.

120

121

```javascript { .api }

122

/**

123

* Spreads array values as arguments to callback

124

* @param promise - Promise that resolves to array

125

* @param fulfilled - Callback receiving spread array elements as arguments

126

* @param rejected - Optional rejection handler

127

* @returns Promise for callback result

128

*/

129

function Q.spread(promise, fulfilled, rejected);

130

131

/**

132

* Instance version that spreads promise array values as function arguments

133

* @param fulfilled - Callback receiving spread elements as arguments

134

* @param rejected - Optional rejection handler

135

* @param ms - Optional timing estimate

136

* @returns Promise for callback result

137

*/

138

promise.spread(fulfilled, rejected, ms);

139

```

140

141

**Usage Examples:**

142

143

```javascript

144

const Q = require("q");

145

146

// Static version

147

const arrayPromise = Q.all([

148

fetchUserName(),

149

fetchUserAge(),

150

fetchUserEmail()

151

]);

152

153

Q.spread(arrayPromise, (name, age, email) => {

154

console.log(`User: ${name}, Age: ${age}, Email: ${email}`);

155

});

156

157

// Instance version

158

const coordinatesPromise = Q.resolve([10, 20]);

159

160

coordinatesPromise.spread((x, y) => {

161

return calculateDistance(x, y, 0, 0);

162

}).then(distance => {

163

console.log("Distance from origin:", distance);

164

});

165

166

// With error handling

167

const dataPromise = Q.all([fetchA(), fetchB(), fetchC()]);

168

169

dataPromise.spread(

170

(a, b, c) => processData(a, b, c),

171

error => console.error("Failed to fetch data:", error)

172

);

173

```

174

175

### Race Operation

176

177

Returns a promise that resolves or rejects with the first settled promise value.

178

179

```javascript { .api }

180

/**

181

* Returns promise for first fulfilled value from array of promises

182

* @param promises - Array of promises to race

183

* @returns Promise that settles with first settled promise

184

*/

185

function Q.race(promises);

186

```

187

188

**Usage Examples:**

189

190

```javascript

191

const Q = require("q");

192

193

// Race between multiple data sources

194

const racePromise = Q.race([

195

fetchFromPrimaryAPI(),

196

fetchFromBackupAPI(),

197

fetchFromCache()

198

]);

199

200

racePromise.then(data => {

201

console.log("Got data from fastest source:", data);

202

});

203

204

// Timeout pattern with race

205

function timeoutAfter(ms) {

206

return Q.delay(ms).then(() => {

207

throw new Error("Operation timed out");

208

});

209

}

210

211

Q.race([

212

longRunningOperation(),

213

timeoutAfter(5000)

214

]).then(

215

result => console.log("Completed:", result),

216

error => console.error("Failed or timed out:", error)

217

);

218

219

// Race with immediate values

220

Q.race([

221

"immediate",

222

Q.delay("delayed", 100)

223

]).then(winner => {

224

console.log(winner); // "immediate"

225

});

226

```

227

228

## Types

229

230

```javascript { .api }

231

// Settlement state interface

232

interface SettlementState {

233

state: "fulfilled" | "rejected";

234

value?: any; // Present when state is "fulfilled"

235

reason?: any; // Present when state is "rejected"

236

}

237

238

// Spread callback signatures

239

type SpreadCallback<T extends any[]> = (...args: T) => any;

240

```