JS Built-ins
← Array21 / 226
ArrayArray.fromAsyncadvanced

Array.fromAsync() β€” safe collection with fallback

πŸ“– Usage Example
try {
  const arr = await Array.fromAsync([Promise.reject(new Error('oops'))])
} catch (e) {
  console.error(e.message)  // 'oops'
}

Wrap Array.fromAsync() in try/catch to handle rejections from any promise in the iterable.

Array.fromAsync() β€” error handling

When using Array.fromAsync, if any promise in the iterable rejects, the entire operation rejects. A try/catch around the await lets you return a fallback value (like null) instead of propagating the error.

This exercise simulates the pattern synchronously: attempt to map each value, returning null if any mapper throws.

Challenge: Implement safeCollect that takes an array of numbers and an optional flag. When shouldFail is true, return null; otherwise return the array as-is.

safeCollect([1, 2, 3], false) // β†’ [1, 2, 3]
safeCollect([1, 2, 3], true)  // β†’ null
πŸ’‘ Hints (2)
  • β€’ With `Array.fromAsync`, wrap the `await` in a `try/catch` to handle any rejected promise.
  • β€’ Returning `null` from the `catch` block is a common safe-fallback pattern.