我正在尝试从下面获取响应并在函数外部使用。响应是一个对象 - 特别是来自localStorage,有50个项目。
chrome.extension.sendRequest(options, function(response){
console.log('answer back is ' + response.newone199);
console.log(response.newone);
var globalvar = response;
});
console.log(globalvar);
两个console.logs都提供了正确的答案 - 但是如果移动到函数之外我将得到未定义。
我已经尝试了返回全局变量,它也不起作用 - 我读过你不能传递函数外的对象,除非你放入另一个函数?我尝试过,但无法使其正常工作。
有人能指出我正确的方向吗?
答案 0 :(得分:1)
基于this answer我最终只是将我的整个函数包装成如下:
function doSomething(){
chrome.extension.sendRequest(options, function(response){
var thing = response.data;
//Do something with our variable.
//The rest of the function goes here before the next bracket
});
}
我知道这不是最优雅的解决方案,但它对我有用。
答案 1 :(得分:1)
在上面的代码中,假设您在函数范围之外声明 globalvar :
1. var globalvar;
2. chrome.extension.sendRequest(options, function(response){
3. console.log('answer back is ' + response.newone199);
4. console.log(response.newone);
5. globalvar = response;
6. });
7. console.log(globalvar);
然后执行顺序为:1,2,7,...,3,4,6,... 那是你的未定义