lasoweq lasoweq - 1 year ago 121
Node.js Question

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

I want to use flickrapi ( package. I need to authorize it:

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

and I want to use this
variable in my express code

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

How should I do it?

Answer Source

Modular approach:

Put your flickr connectivity code separate:


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:


Now Simply access flickr object anywhere by simply requiring it.


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

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download