返回回调函数Node.js的数据

Hug*_*ugo 2 javascript callback ejs node.js express

我正在使用带有Node.js的500px API模块,我正在尝试获取特定用户的照片.我面临功能,回调和范围的问题......我有这段代码:


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

我想把我的变量拿出来dataPx并在我的ejs模板中使用它:


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

如果有人能解释我如何做到这一点以及这种事情在JavaScript中是如何工作的那就太酷了!

谢谢

Zee*_*mon 6

我不知道您的应用程序结构如何,但First Simple解决方案如下:

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});
    });
  });
Run Code Online (Sandbox Code Playgroud)

或者采用更好更清洁的方法,使用q库,

裹api500px.photos.getByUsername在一个承诺如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

并将其用作:

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

快乐帮助!