TL;博士

// async キーワードで同期処理のできる関数を定義
window.onload = async (e) => {
    // chrome.storage.sync.get に await をつけて同期処理に
    // chrome.storage.sync.get は Promise を返すので、戻り値は .then() で取得する
    const domainList = await chrome.storage.sync.get('domainList').then(item => item['domainList']);
    console.log(domainList);
}

我认为这种写作方式很容易,因为new Promise() 是不必要的。

观点

第1部分

chrome.storage.sync.get()如果函数保持原样,它将是异步的Promise1由于返回的是asyc,所以包裹在一个函数中,乘以asyc,实现同步处理,然后用.then()获取storage内的值。

这一次,我希望在渲染 HTML 后运行 javascript,所以我在 window.onload 事件的匿名函数中添加了 async

第2部分

.then(item => item['domainList']) 使用与chrome.storage.sync.get('domainList') 中指定的相同的键'domainList' 指定要从存储在sync 的对象中检索的值2.

也是一个箭头函数表达式,定义了then() 的回调3通过不使用{} 包围右侧,我们使用允许右侧的值作为then() 的返回值而不使用return 的表示法。

例子

window.onload = async (e) => {
    // domainList1 と domainList2 は同じ値になる
    const domainList1 = await chrome.storage.sync.get('domainList').then(item => item['domainList']);
    const domainList2 = await chrome.storage.sync.get('domainList')
                            .then(item => {
                                return item['domainList']
                            });
}

参考

  1. 承诺 - JavaScript | MDN

  2. chrome.storage-Chrome 开发者

  3. 箭头函数表达式 - JavaScript | MDN


原创声明:本文系作者授权爱码网发表,未经许可,不得转载;

原文地址:https://www.likecs.com/show-308626809.html

相关文章:

  • 2021-07-26
  • 2021-06-03
  • 2021-09-07
  • 2021-12-21
  • 2022-12-23
  • 2022-12-23
  • 2022-01-22
  • 2022-12-23
猜你喜欢
  • 2021-10-16
  • 2022-12-23
  • 2022-02-08
  • 2022-02-10
  • 2021-09-12
  • 2021-11-26
  • 2022-01-14
相关资源
相似解决方案