Node.js / express,javascript回调函数没有被执行

时间:2016-04-01 20:19:16

标签: javascript node.js express

/* GET home page. */
router.get('/home/', function(req, res, next) {

  var code = req.query.code;

  req.SC.authorize(code, function(err, accessToken) {
    if ( err ) {
      throw err;
    } else {
      req.session.oauth_token = accessToken;
      // Client is now authorized and able to make API calls
      //res.render('home', { token: accessToken });
      var url = 'https://api.soundcloud.com/me?oauth_token=' + accessToken;
      requestify.get(url).then(function(response){
        var user = response.getBody();
        req.session.user = user;
        var user_url = config.base_url + '/api/users/add';
        var options = { user: user };
        requestify.post(user_url, options).then(function(response){
          console.log("done with users/add")

          var href = 'https://api.soundcloud.com/users/' + user.id 
              +  '/favorites?client_id=' + config.auth.client_id + '&linked_partitioning=1&limit=200';
          soundcloud.getCollection(req, res, [], href, function(collection){
            console.log("can't get here...");
            //console.log(collection);
            res.json(collection);
            //return collection;
          });
          /*
          var collection_url = config.base_url + '/api/collections/add';
          requestify.post(collection_url, options).then(function(response){
            console.log("done with collections/add")
            res.json(response);
          })
          */
        });
      });
    }
  });

});

function getCollection(req, res, collection, next_href, done){
    console.log("here");

    requestify.get(next_href).then(function(response){
        var updatedCollection = collection.concat(response.getBody().collection);
        if (next_href && updatedCollection.length < 500){ 
            var href = response.getBody().next_href;
            getCollection(req, res, updatedCollection, href);
        }
        else {
            console.log("done");
            done(updatedCollection);
        }
        //res.json(response.getBody());
    });
}

我看到的行为是,集合正确构建,console.log(“done”)显示在控制台中,但在我调用done(updatedCollection)之后,我传入的回调函数没有得到执行。没有打印语句,没有json渲染。你们看到问题是什么吗?

1 个答案:

答案 0 :(得分:3)

您在没有回调的情况下递归调用getCollection函数,因此下次调用时,done未定义。

将回调传递给递归调用

function getCollection(req, res, collection, next_href, done) {

    requestify.get(next_href).then(function(response){
        var updatedCollection = collection.concat(response.getBody().collection);
        if (next_href && updatedCollection.length < 500){ 
            var href = response.getBody().next_href;
            getCollection(req, res, updatedCollection, href, done); // <- HERE
        } else {
            console.log("done");
            done(updatedCollection);
        }
        //res.json(response.getBody());
    });
}