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']
});
}
参考
原创声明:本文系作者授权爱码网发表,未经许可,不得转载;
原文地址:https://www.likecs.com/show-308626809.html