DEV Community

John Kazer
John Kazer

Posted on

Async functionality - currying that makes sense

There are a range of ways in JavaScript to handle or express delayed activity:

  • Callbacks (pass a single function to be used later)
  • Promises
  • Async/Await
  • setTimeout
  • Subscription
  • Push notifications
  • etc.

Another way of providing delayed functionality is "currying". Regardless of the many tutorials about how currying works, the main point is to handle a delay in the application of functionality. I just use the Ramda curry function and don't worry about the mechanics.

In fact, currying can work quite well in an asynchronous environment because the delay is fundamental. You may often be subject to waiting for all the information before executing full functionality.

An example might be pre-configuring a button in React, but needing to receive a user selection from a drop-down that completes the configuration before adding it to the UI. The user's selection might define the button's label text for example.

Another example is making use of the difference between configuring how to process an array, and actually doing the processing.

import { curry } from 'ramda'

const listOfData = [1, 2, 3]
// the core function expressing the functionality we want
// but wrapped by the 'curry' function
const processMyList = curry((configParam, listItem) => {
    return configParam + listItem
})
const fetchedConfigParam = await someAsyncronousFunction() // fetches a number
// using 'curry' creates a new function we can use later
const incrementListOfNumbers = processMyList(fetchedConfigParam) // provide the configParam arg
// do the processing
const processedList = listOfData.map(number => {
    return incrementListOfNumbers(number) // provide the listItem arg
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)