javascript - When shall one make a function return a promise? -


i'm getting generators , promises , i've kind of gotten handle of how work. it's time make own functions utilize these. there guides out there explaining how make them , discuss appropriate times when 1 should used.

i know has lie promises generators code writing synchronous (among other things).

so question is: when should , when should not promisify function have?

from understanding if cpu being utilized 100% function should not promisify there no point.

if cpu being blocked , waiting external such waiting download guess should promisify function.

promises should used when have asynchronous operations want execute in sequence. operations costly, writing file/db, making request service, forth, have asynchronous api, since doing synchronously block single-threaded javascript application. in cases, either use promises cleaner code, use named functions , explicitly call them 1 after other callbacks or don't use , have pyramid of doom full of callbacks.

so, imagine want user data token recieve in http request, posts regarding him, , special holiday offer 1 of other services wanna stick in there request. promises,

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 error     }); }) 

this post paint clearer picture of how , when should use promises.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -