Skip to content

Instantly share code, notes, and snippets.

@Rob-ot
Created November 22, 2013 19:11
Show Gist options
  • Save Rob-ot/7605212 to your computer and use it in GitHub Desktop.
Save Rob-ot/7605212 to your computer and use it in GitHub Desktop.
async.memoize saves the day!

Say you have some code like this:

functiongetData (cb) {
  console.log("doing long async operation")
  http.get('/user', cb)
}

getData(function(err, data) {
  console.log("got 1")
})

getData(function(err, data) {
  console.log("got 2")
})
doing long async operation
doing long async operation
got 1
got 2

getData is a nice abstraction but every function that calls it will do an additional http request!

async.memoize

var getData = async.memoize(function(cb) {
  console.log("doing long async operation")
  http.get('/user', cb)
})

getData(function(err, data) {
  console.log("got 1")
})

getData(function(err, data) {
  console.log("got 2")
})
doing long async operation
got 1
got 2

async.memoize saves the day!

var getData = async.memoize(function (cb) {
console.log("doing long async operation")
setTimeout(cb, 2000)
})
getData(function (err, data) {
console.log("got 1")
})
getData(function (err, data) {
console.log("got 2")
})
@xjamundx
Copy link

What if getData takes an argument? Like getUserData(id, cb)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment