简体   繁体   中英

Node.js / express, javascript callback function not getting executed

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

Behavior I'm seeing is, the collection is properly built up, the console.log("done") is showing up in the console, but after I call done(updatedCollection), the callback function I pass in does not get executed. No print statement, no json rendering. Do you guys see what the issue is?

You're recursively calling the getCollection function without the callback, so the next time it's called, done is undefined.

Pass on the callback to the recursive calls as well

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM