簡體   English   中英

Node.js / Express,JavaScript回調函數未執行

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

我看到的行為是,集合已正確構建,console.log(“ done”)在控制台中顯示,但是在我調用done(updatedCollection)之后,傳入的回調函數無法執行。 沒有打印語句,沒有json呈現。 你們看到了什么問題嗎?

您遞歸地調用了沒有回調的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());
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM