回调函数和异步请求的使用 [英] Usage of callback functions and asynchronous requests

查看:173
本文介绍了回调函数和异步请求的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用使用Facebook API的 node.js 应用程序。在我的代码的一部分,我需要从一个常用的函数返回 access_token 。也就是说,很多其他功能需要调用此函数来检索Facebook访问令牌。

I am working with a node.js application that uses Facebook APIs. In one part of my code I need to return the access_token from a common function. That is, a lot of other functions need to call this function to retrieve the Facebook access token.

以下是我的代码:

function getAccesstoken(code) {
    var options = {
        host: 'graph.facebook.com',        
        path: '/oauth/access_token?client_id=xxxx&redirect_uri=xxxxxx&client_secret=xxxxx&code='+code.toString()
    };

    var acc_token = ''

    https.get(options, function(resp) {
        resp.on('data', function(d) {                                    
            acc_token = acc_token+d.toString()
        });    

        resp.on('end', function() {
            var expiry_index = acc_token.indexOf('&expires=')

            acc_token = acc_token.substring(0, expiry_index)            
        });
    });        

    return acc_token.toString()
}

code> https.get 调用是异步的,函数总是返回一个空字符串。这样做最好的方法是什么?

Since https.get call is asynchronous, function always returns an empty string. What should be the best way to do this?

推荐答案

提供一个回调函数给你的getAccesToken函数,然后调用函数响应已经结束,并将acc_token传递给该函数。

well supply a callback function to your getAccesToken function and call the function after the response has ended and pass acc_token to that function..

 function getAccessToken(code,cb){
    .....
    resp.on('end',function(){
       .....
       cb(null,acc_token)
    })
 }

然后调用您的函数,如

getAccesToken("whatever",function(err,token){
  console.log("got token", token)
})

这篇关于回调函数和异步请求的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆