2014-03-19 56 views
0

我需要讓我的ExpressJS應用POST請求後的請求......但我想爲了與他們一起工作的回調函數外體結果...請與ExpressJS

我認爲我需要同步功能...

var TOKEN; 

exports.getToken = function(req, res){ 

    var postData = { 
     client_id: CLIENT_ID, 
     client_secret: CLIENT_SECRET, 
     grant_type: 'authorization_code', 
     redirect_uri: REDIRECT_URI, 
     code: CODE 
    } 

    var url = 'https://api.instagram.com/oauth/access_token'; 

    // Make my sync POST here and get the TOKEN 
    // example : 
    // request.post({....}, function(err, res, body){ TOKEN = body; }); 

    // console.log(TOKEN); 

    res.render('index', {title: '****'}); 
} 

回答

1

看看異步庫。系列或瀑布功能是你想要的。

https://github.com/caolan/async#waterfall

東西沿着這些路線:

async.waterfall([ 
function (callback) { 
    var postData = { 
     client_id: CLIENT_ID, 
     client_secret: CLIENT_SECRET, 
     grant_type: 'authorization_code', 
     redirect_uri: REDIRECT_URI, 
     code: CODE 
    } 
    var url = 'https://api.instagram.com/oauth/access_token'; 
    //pass the body into the callback, which will be passed to the next function 
    request.post(postData, function (err, res, body) { callback(null,body); }); 
}, 
function (token, callback) { 
    //do something with token 
    console.log(token); 
    callback(null); 
} 
], function (err, result) { 
    // result now equals 'done' 
    res.render('index', { title: '****' }); 
}); 
+0

謝謝你,它的工作原理! – tonymx227