javascript - Using Promises / Node -


i'm trying find way/best way use promises in node application.
i'll honest, don't 100% understand promises, i'm getting better more practice.

what i'm looking after logs in:

  1. get facebook access token
  2. access users profile, update user document in mongodb or create new user document if don't exist
  3. access facebook friends list , cross reference "friends" document in mongodb.

problem have point 3, require access token point 1 , user document either existing or newly created in point 2 pass third function.

my chain of functions looks like:

getaccesstoken(req) .then(function(accesstoken){  getuserprofile(req, accesstoken)  .then(finduser.bind(null, req, res))   .then(...)  }); 

getaccesstoken returns "accesstoken" facebook. getuserprofile returns user facebook. finduser finds existing or creates new user document in mongodb.

how return existing or newly created user object , pass through coupled accesstoken in form of promise?

you can either nest promises:

getaccesstoken(req) .then(function(accesstoken) {   return getuserprofile(req, accesstoken)   .then(finduser.bind(null, req, res))   .then(function(user) {     // use accesstoken & user   }) }); 

or store resolved values in outer scope:

var _accesstoken; getaccesstoken(req) .then(function(accesstoken) {   _accesstoken = accesstoken;   return getuserprofile(req, accesstoken); }) .then(finduser.bind(null, req, res)) .then(function(user) {     // use _accesstoken & user }); 

remember return nested promise.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -