logo CCISEL
  • Home
  • Team
  • Academia
  • News
  • Archive
  • Contacts
  

Stretching Async/Await With Lambdas

July 9, 2020 | Miguel Gamboa

  1. Can you figure out the difference resulting from the execution of the following code snippets? TIP: one performs requests concurrently and the other sequentially. Which one and why?

  2. Is there any difference if you replace the arrays pipeline (i.e. map().reduce()) that performs eagerly with an iterable pipeline (such as C# Linq) performing lazily? Is it still sequential or still concurrent? Why?

If you are a Java, Kotlin, C# or JavaScript developer you may find more use cases and foundations in the article of CCISEL engineer Miguel Gamboa about “Stretching Async/Await With Lambdas”


async function fetchAndSumBodiesLengthsλ(urls) {
  return urls
    .map(async (url, i) => {
      const resp = await fetch(url)  // 1. Fetch url
      const body = await resp.text() // 2. Read body
      return body.length             // 3. Get length
    })
    .reduce(async (l1, l2) => {
      return await l1 + await l2     // 4. Sum lengths
    })
}

async function fetchAndSumBodiesLengths(urls) {
  let sum = 0
  for (const url of urls) {
    const res = await fetch(url)  // 1. Fetch url
    const body = await res.text() // 2. Read body
    const length = body.length    // 3. Get length
    sum += length                 // 4. Sum lengths
  }
  return sum
}

Copyright © CCISEL 2025