2013-10-19 1 views
-1

나를 멍청한 놈 전화 그러나 나는이 작업을 얻이 수없는 것 :크롬 storage.get 범위 문제

var value = ""; // Tried this 
function getKey(key) { 
    var value = ""; // And this 
    chrome.storage.local.get(key, function (data) { 
    var value = data[key]; 
    console.log(value); // This prints the correct value 
    }); 
    console.log(value); // But this will always print null 
} 

어떤 생각을 왜?

답변

3

chrome.storage.local.get 호출은 비동기입니다. getKey 함수는 콜백이 실행되기 전에 반환되므로 값이 설정되지 않습니다.

function getKey(key, callback) { 
    chrome.storage.local.get(key, function(data) { 
    var value = data[key]; 
    callback(value); // This calls the callback with the correct value 
    }); 
} 

을 그리고 getKey로 호출과 같이 나타납니다 :

getKey에 값을 반환하기 위해 당신과 같이 재정의 할 필요가

getKey("some_key", function(value) { 
    // do something with value 
}); 
+0

방금 ​​알아 냈습니다. 내가 동기로 작동하도록 할 수 있으면 좋겠어? 또는 적어도 getKey가 값을 반환하는지 확인하십시오. –

+1

getKey를 비동기 적으로 호출해야합니다. 선언을 getKey (key, callback)로 변경하고 "value"를 리턴하지 않고 콜백으로 전달하십시오. – rgeorgy

0

여기에 2 문제가 있습니다. (1) 범위 문제. (2) 비동기 문제. 시험해보기 :

// define getKey() 
function getKey(key, callback) { 
    chrome.storage.local.get(key, function (data) { 
    callback(data[key]); 
    }); 
} 

// use getKey() 
function setDocumentTitle(title) { 
    document.title = title; 
} 

getKey('title', setDocumentTitle);