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:
- get facebook access token
- access users profile, update user document in mongodb or create new user document if don't exist
- 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
Post a Comment