2016-09-03 216 views
0

我试图返回一个我所做的api调用的结果,但我一直在获取undefined作为输出。这里的代码:从回调函数返回一个变量javascript函数

function getProjects() { 
    var message; 
    gapi.client.dolapoapi.getProject({ 
    'appid': "test4" 
    }).execute(function(resp) { 
    if (!resp.code) { 
     //get the response and convert it to a string 
     message = JSON.stringify(resp); 
     //console.log(resp); i get the correct output here 
    } 
    //console.log(message); i get the correct output here 
    }); 
    //console.log(message); it returns undefined. 
    return message; 
} 

我不知道什么可能是错的。但我想要做的就是回到它的位置分配后的消息变量是什么:

message = JSON.stringify(resp); 

回答

2

传递一个函数作为回调,当异步操作完成的呼叫与数据作为参数的函数。

function getProjects(callback) { 
    var message; 
    gapi.client.dolapoapi.getProject({ 
    'appid': "test4" 
    }).execute(function(resp) { 
    if (!resp.code) { 
     //get the response and convert it to a string 
     message = JSON.stringify(resp); 
     //console.log(resp); i get the correct output here 
    } 
    if(callback && typeof callback == "function") { 
     callback(message); 
    } 
    }); 
} 

getProjects(function(message) { 
    //using a callback to get the data 
    console.log(message); 
}); 
+1

谢谢。能够实施它。 –

+0

@DolapoToki upvote和接受,如果它的工作 – Iceman