如何使用async和await获取Chrome扩展程序的信息?
[chrome.instanceID.getID]
[chrome.storage.sync.get]
我们尝试了这段代码:
async function test()
{
let _r = await chrome.instanceID.getID();
return _r;
}
let _pc_id = test();
但是
_pc_id
返回一个承诺。我们找不到任何方法来获取其中的价值。我们该怎么做?
您可以像这样获取实例ID,但不能将其存储在变量中以在承诺范围之外使用它,AFAIK。您可能想阅读以下内容:将 Promise 中的数据保存在变量中
如果你想使用 Promise 的返回值,你需要在 Promise 中或者在 Promise 之后的
.then()
中执行,至少我是这样做的。
chrome.instanceID.getID
示例:
chrome.instanceID.getID((instance_id) => {
console.log(instance_id);
// Execute your other related code here
});
或
var promise = chrome.instanceID.getID();
promise.then((instance_id) => {
console.log(instance_id);
// Execute your other related code here
});
或
chrome.instanceID.getID()
.then((instance_id) => {
console.log(instance_id);
// Execute your other related code here
});
chrome.storage.sync.get
示例:
chrome.storage.sync.get('myKey', function(items) {
var key = items.myKey;
// Below code is an example, change it to your needs
if (key) {
console.log(key)
} else {
key = createKey(); // a custom function that generates keys
chrome.storage.sync.set({myKey: key}, function () {
console.log(key);
});
}
};
问题是您没有等待异步函数。将函数标记为异步会自动将其返回值转换为承诺。
很大程度上取决于您想在哪里使用此代码。如果您使用模块,您现在可以只使用顶级等待:
const iID = await chrome.instanceID.getID();
console.log(iID);
或者作为一个函数,如果它可能在代码执行期间更新:
const getIID = await () => chrome.instanceID.getID();
console.log(getIID);
但是,如果您使用基本脚本,则需要在异步函数或回调中执行您想要的操作和/或填充全局变量。不过,对于需要填充的全局变量,您需要考虑变量可能为空。以下是一些选项:
chrome.instanceID.getID().then((id) => {
// do stuff with id
});
var {getID} = chrome.instanceID;
async function foo() {
const myID = await getID();
// do stuff with myID
}
var myID;
async function foo() {
if (!myID) myID = await chrome.instance.getID();
// do stuff with myID
}