2

I'm using the 500px API module with Node.js and I'm trying to get photos of a specific user. I'm facing issue with function, callback and scope... I've this code :


    api500px.photos.getByUsername ('username', {'sort': 'created_at', 'image_size': '3'}, function(error, results) {
        if (error) {
            console.log(error);
            return;
        }
        var dataPx = results.photos;
    });

I want to get out my variable dataPx and use it in my ejs template :


    app.get('/materialize', function(req, res) {
        res.render('materialize.ejs', {dataPx: dataPx});
    });

If someone could explain me how to do that and how this kind of things work in JavaScript it would be cool !!!

Thx

Hugo
  • 163
  • 4
  • 16

1 Answers1

6

I don't know how is your app structure, but First Simple solution is below:

app.get('/materialize', function(req, res) {            
    api500px.photos.getByUsername ('username', {'sort': 'created_at', 'image_size': '3'}, function(error, results) {
        if (error) {
            console.log(error);
            return;
        }
        var dataPx = results.photos;
        res.render('materialize.ejs', {dataPx: dataPx});
    });
  });

OR adopt better and cleaner approach, use q library,

Wrap api500px.photos.getByUsername in a promise as:

function getUserPhotosAsync() {
  var deferred = q.defer();
      api500px.photos.getByUsername ('username', {'sort': 'created_at', 'image_size': '3'}, function(error, results) {
            if (error) {
                deferred.reject(error);
            }
            deferred.resolve(results.photos);
        }); 
  return deferred.promise;
}

And use it as:

   app.get('/materialize', function(req, res) {
      getUserPhotosAsync().then(function(dataPx) { //looks cool isn't it?
        res.render('materialize.ejs', {dataPx: dataPx});
      });
    });

Happy Helping!

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57