使用chrome.storage.sync.get分配值

时间:2019-01-15 19:33:00

标签: javascript google-chrome-extension race-condition

我正在尝试使用chrome.storage.sync获取值集,但是当我尝试将其分配给obj属性(或通过const分配给变量)时,却变得未定义。

示例代码:

const MyObj = {};

function getSignInTimeStamp() {
  chrome.storage.sync.get('expires', (result) => {
    console.log(`Value currently is ${result.expires}`);
    MyObj.signInStamp = result.expires;
  });
}

function doSomething() {
  getSignInTimeStamp();
  console.log(MyObj); // <-- shows value here in console
  const nowTime = new Date();
  console.log(MyObj.signInStamp); // <-- shows as undefined in console
  if (MyObj.signInStamp || (MyObj.signInStamp - nowTime) >= 0) {
    // a bunch of other stuff that fails because the comparison evaulates as NaN
  }
}

我假设存在比赛条件,但是我已经尝试过了,但是也没有用:

getSignInTimeStamp().then((result) => {
  myObj.signInStamp = result.expires;
});

chrome.storage.sync.get取回值并将其分配给在get块外使用的变量的正确方法是什么?

0 个答案:

没有答案