The type of elements in the input array
The type of elements in the resulting array
A Promise resolving to the transformed array
const userIds = [1, 2, 3, 4, 5];
const userDetails = await ArrayUtil.asyncMap(
userIds,
async (id, index) => {
console.log(
`Fetching user ${id} (${index + 1}/${userIds.length})`,
);
const response = await fetch(`/api/users/${id}`);
return await response.json();
},
);
console.log("All users fetched:", userDetails);
contracts/common.md#principled-implementation The closure result of each element is pushed in iteration order, so the output order equals the input order, which holds because the calls are sequential.
Transforms each element of an array using an asynchronous function to create a new array.
Similar to JavaScript's native map but processes asynchronous functions sequentially. Each element's transformation is completed before proceeding to the next element, ensuring order is maintained.
Processing cost: Each of N elements invokes its mapper once in sequence and stores one result: O(N) bookkeeping and output space.
Resource ownership: The invocation awaits one callback at a time and retains only its partial output and current call; success transfers the output to the caller and rejection releases local state. Callback-owned external resources remain the callback owner’s responsibility.