-2
var curline;
chrome.storage.local.get("value",function(item)
{
    window.curline=item["value"];

});
alert(curline);

I want to set the curline with item["value"],this code is in theinject.js,thanks.

Louise
  • 91
  • 1
  • 2
  • 9
  • I agree that the duplicate is probably what OP is looking for, but I'll point out that the `get` function should not be used to `set` the variable. – Teepeemm May 04 '15 at 14:28

1 Answers1

1

chrome.storage API is asynchronous. The callback is executed later, after you alert.

Which means you must alert the result in the callback you pass :

var curline;
chrome.storage.local.get("value",function(item)
{
    window.curline=item["value"];
    alert(curline);
    // here you may use curline, or pass it as argument to other functions 
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    ok,I see,but I can't use the curline out of the chrome.storage.local.get scope,it is very unconvenient.What I want is to use the curline out of that scope,not just alert it.Is there anyway to approch my need?Thanks. – Louise May 04 '15 at 10:13
  • @Louise Pass it as argument to other functions needing it for example. – Denys Séguret May 04 '15 at 10:13
  • @Louise You need to chain your calls (so basically, yes, only use it in the scope). Alternatively, you can try Promises, but conceptually they serve the same purpose. Carefully read the question linked in the duplicate notice. – Xan May 04 '15 at 10:16
  • And to be clear : there's no way to do anything in JavaScript without understanding this asynchronicity problem. Do read until you get it. – Denys Séguret May 04 '15 at 10:17
  • @dystroy,I'm cleared,it seem it is different from HTML5's localstorage,thanks. – Louise May 04 '15 at 10:37
  • @Xan you help me twice,lol – Louise May 04 '15 at 10:40