3

I'm getting into generators and promises now and I've kind of gotten the handle of how they work. Now it's time to make my own functions which utilize these. There are guides out there explaining how to make them and what they are for but however they rarely discuss the appropriate times when one should be used.

I know this mainly has to lie with promises as generators just help the code writing look synchronous (among other things).

So my question is: When should I and when should I not promisify a function I have?

From my understanding if the cpu is being utilized 100% by the function then I should NOT promisify as there is no point.

If the cpu is being blocked and is waiting for something external such as waiting for something to download then I guess I should promisify that function.

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • JavaScript is very IO heavy. Lots of calls to remote resources. For those types of operations it makes total sense to create a promise. If you have CPU bound operations, you can look at using webworkers in the browser or the child_process module in node.js. – lintmouse Sep 29 '15 at 22:44
  • "If the cpu is being blocked and is waiting for something external such as waiting for something to download then I guess I should promisify that function." --- what would be an example for that? All IO is asynchronous already, so you basically have no choice. – zerkms Sep 29 '15 at 23:28

1 Answers1

1

Promises should be used when you have asynchronous operations that you want to execute in a sequence. Operations that are costly, like writing to a file/db, making a request to another service, so forth, usually have an asynchronous api, since doing those synchronously would block your single-threaded javascript application. In those cases, you either use something like promises for a cleaner code, you use named functions and explicitly call them one after the other as callbacks or you don't use anything and have yourself a pyramid of doom full of callbacks.

So, imagine you want to get the user data from the token you recieve in the http request, then get all the posts regarding him, and get a special holiday offer from one of your other services that you wanna stick in there with the request. With promises, you could do something like

router.get('/activities', function(req, res){           
    userRepo.findByToken(token).then(checkForOffer).then(activityRepo.getUserPosts).then(function(composite){
        res.send({activities: composite.activities, offer: composite.offer});
    }).fail(function(err){
        //handle the error
    });
})

This post paint a clearer picture of how and when you should use promises.

Community
  • 1
  • 1
Titus Popovici
  • 149
  • 2
  • 11