如何使用express在节点js中执行连续的回调函数?

时间:2016-08-22 09:42:15

标签: node.js express callback slack-api

我试图用机器人构建一个松弛的应用程序,为此我需要执行几个回调函数,但它没有设法启动第三个。前两个效果不错,但最后一个从未开始,我不知道为什么。 我使用快递。

这是我的代码:



var app = express();
app.use(bodyParser());

var port = process.env.PORT || 5000;


//Fonctions de Callback
boutonSlack = function(req, res,next) { //Show the slack button to install the app
    res.send('<a href="https://slack.com/oauth/authorize?scope=bot,incoming-webhook,commands,'
                                                         +'src="https://platform.slack-edge.com/img/add_to_slack.png" '
                +'srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, '
                +'https://platform.slack-edge.com/img/add_to_slack@2x.png 2x" /></a>');
    console.log('cb0:le bouton slack s\'affiche');
    next();
    app.get('/redirect/',recupCode);
};

recupCode = function(req, res, next){//get the code parameter to perform the oauth process
    console.log(req.query.code);
    process.env.CODE = req.query.code;
    console.log('cb1 : le code est récupéré');
    res.send('cb1 : le code est récupéré');
    https.get('https://slack.com/api/oauth.access?client_id='+process.env.CLIENT_ID+'&client_secret='+process.env.CLIENT_SECRET+'&code='+process.env.CODE, (res) => {
        res.on('data', (chunk) => {
            var result = JSON.parse(chunk);
            console.log(JSON.stringify(result));
            process.env.SLACKTOKEN = result.access_token;
            process.env.SLACK_BOT_TOKEN = result.bot.bot_access_token;
        });
    });
    console.log(process.env.SLACKTOKEN);
    console.log(process.env.SLACK_BOT_TOKEN);
    console.log('cb2 : le token est récupéré')
    next();
    app.get('/',ouvertureWebsocket);
};

ouvertureWebsocket = function (req, res, next) {//perform the rtm.start slack method to open the websocket
    console.log('cb3 : ouverture du web socket');
    res.send('cb3 : ouverture du websocket');
    https.get('https://slack.com/api/rtm.start?token='+process.env.SLACK_BOT_TOKEN, (res) => {
        res.on('data', (chunk) => {
            var result = JSON.parse(chunk);
            console.log(JSON.stringify(result));
        });
    });
    res.end(); 
}

app.get('/',boutonSlack);
app.listen(port, function () {
  console.log('Ready, listenning port '+port);
});
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我建议你进一步深入研究异步代码在nodejs中的工作原理

在您的情况下,您必须放置

a b  
1 1  1
  2  1
  3  None
  4  None
2 1  None
  2  None
  3  1
  4  None
3 1  None
  2  None
  3  None
  4  1

console.log(process.env.SLACKTOKEN); console.log(process.env.SLACK_BOT_TOKEN); console.log('cb2 : le token est récupéré') next(); app.get('/',ouvertureWebsocket); 数据回调中。

https.get('https://slack.com/api/rtm.start?token...