I'm writing a small app in node.js that interfaces with Vimeo's API. I installed the official Node SDK from vimeo using npm install vimeo-api. Everything is working fine, but now I want to change the program flow to be more "promise like". For example, I would like for my program to wait until it receives the OAuth access token returned by the Vimeo.accessToken method before it executes any new code. How can I acheive this?
Here is some code driving the retrieval of the access token--very much taken from the examples on the SDK github page:
var vmoapi = require('vimeo-api'),
vmo = new vmoapi(VMO_CLIENT_ID, VMO_CLIENT_SECRET);
.
.
.
function getAccessToken(code, redirectURI){
vmo.accessToken(code, redirectURI, function(err, token){
if (err) {
console.log("Vimeo API Error\n" + err);
return;
}
if (token.access_token){
console.log(nutil.inspect(token));
vmo.access_token = token.access_token;
user = token.user;
userScopes = token.scope;
return token;
}
})
}
In node.js how can I do something like the following:
getAccessToken(myCode, "http://someplace.com").done(function(data){
console.log("Access token" + nutil.inspect(data));
})
I thought maybe I would use Kris Kowal's Q library, but am not certain about how to go about implementing it so that my app flows in the manner that I would like.
So after reading Q's documentation and some examples, here is what I implemented and it seems to be working!
var vmoapi = require('vimeo-api'),
vmo = new vmoapi(VMO_CLIENT_ID, VMO_CLIENT_SECRET),
.
.
.
deferred = Q.deferred();
.
.
.
function getAccessToken(code, redirectURI) {
vmo.accessToken(code, redirectURI, function(err, token) {
if (err) {
console.log("Vimeo API Error\b" + err);
deferred.reject(new Error(err));
}
if (token.access_token){
vmo.access_token = token.access_token;
user = token.user;
userScopes = token.scope;
deferred.resolve(token);
}
})
return deferred.promise;
}
getAccessToken(parsedURL.query.code, vmoRedirectURI)
.then(function(data){
console.log("Vimeo access token:\n" + nutil.inspect(data))
});
The solution involves use the Q.deferred() object and then setting up the .reject and .resolve methods within the Vimeo.accessToken callback function. Then at the end of the function that calls the Vimeo.accessToken method, return the deferred.promise.