lasoweq lasoweq - 1 month ago 17
Node.js Question

How to use an asynchronous response value in an `app.get` callback

I want to use flickrapi (https://www.npmjs.com/package/flickrapi) package. I need to authorize it:

Flickr.tokenOnly(flickrOptions, function(error, flickr) {
//I need this flickr variable
});


and I want to use this
flickr
variable in my express code

app.get('/', function (req, res) {
//do something with flickr
});


How should I do it?

Answer

Modular approach:

Put your flickr connectivity code separate:

flickr-public.js

var Flickr = require("flickrapi"),
    flickrOptions = {
      api_key: "API key that you get from Flickr",
      secret: "API key secret that you get from Flickr"
    };

module.exports = (function(){        
    Flickr.tokenOnly(flickrOptions, function(error, flickr) {
      //handle error here
      console.log('Flickr Object Obtained');
      return flickr;
    });
})();

Note: Better instantiate the flickr object in your app.js file. So that the object gets created immediately when server starts. As this flickr object is for public API only and does not need authentication again and again.

You can instantiate the flickr object by simply requiring it in app.js file:

require('./flickr-public');

Now Simply access flickr object anywhere by simply requiring it.

routes.js

const flickr = require('../path-to/flickr-public');

app.get('/', function (req, res) {
  //use flickr object to perform actions.
});

Explanation:

From the node.js documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file. Multiple calls to require('foo') may not cause the module code to be executed multiple times.