2016-04-01 70 views
-1

的Node.js /快遞,JavaScript回調函數沒有得到執行

/* 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()); 
 
    }); 
 
}

行爲,我看到的是,收集正確建立,控制檯。日誌(「完成」)顯示在控制檯中,但在我調用完成(updatedCollection)後,我傳入的回調函數沒有得到執行。沒有打印語句,沒有json渲染。你們看到了什麼問題嗎?

+0

請嘗試做(updatedCollection()); –

+1

'updatedCollection'是一個數組(我假設),而不是一個函數@BarışÇırıka。 – Andy

+0

@我現在明白了。我讀了updateCollection。 –

回答

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()); 
    }); 
} 
相關問題