【问题标题】:JS Promise doesn't chain while working chrome.storage.syncJS Promise 在工作 chrome.storage.sync 时不会链接
【发布时间】:2019-10-12 17:41:39
【问题描述】:

我正在尝试进行承诺链接,但不知何故,使用chrome.storage.sync.get 的异步调用总是稍后返回。这是我认为应该是正确的顺序:

  1. 创建一个元素并附加到正文
  2. 致电chrome.storage.sync
  3. 根据 2) 结果,在 1) 中创建的元素上触发一些事件

我已经尝试将新的 Promise 放入 2) 步骤,但没有成功。 console.log 总是以错误的顺序返回。比如:

  1. // insertCheckbox 完成
  2. //启动promise chrome.storage.sync
  3. //未定义
  4. // 结果 asnyc: ...

这是我的尝试:

const pr = new Promise(resolve => {
  this.createCheckbox();
  console.log('insertChecbox done')
  resolve();
});

pr
  .then( resolve => {
    console.log("start promise chrome.storage.sync");

    return new Promise( resolve => {
      return resolve(chrome.storage.sync.get(["code", "isAutocheck"], result => {
        console.log('result async: ', result );
        return result
      }));
    });
  })
  .then( result => {
    console.log(result);
    console.log('This always run before the `chrome.storage.sync` finishes loading`)
    if (result.isAutocheck) {
      const domCheckbox = this.getCheckboxElement();
      domCheckbox && domCheckbox.click();
    }
  });

我想分离 chrome.storage.sync 的结果,因为我需要处理其他事情,而不是让这个回调太复杂

【问题讨论】:

    标签: javascript asynchronous promise chaining


    【解决方案1】:

    感谢您注意到这个问题,我通过在我的第一个 .then 中进行了一些更改,明确地解决了 chrome.storage.sync.get 的结果,而不是全部,找到了解决方案。

    pr
      .then( () => {
        return new Promise( resolve => {
          return chrome.storage.sync.get(["code", "isAutocheck"], result => {
            console.log('result async: ', result );
            return resolve(result)
          });
        });
      })
      .then(...);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      相关资源
      最近更新 更多