Chrome扩展代码执行顺序异常:指定日志语句提前执行问题
Chrome扩展代码执行顺序问题解决
问题原因
你遇到的问题核心在于:chrome.storage.local.get和chrome.identity.getProfileUserInfo都是异步回调式API——它们启动后不会阻塞主线程,而是等后台操作完成后才会调用传入的回调函数。而你放在最后的那两句consoleLog是同步执行的,主线程不会等异步回调跑完就直接执行它们,这时候tenant还没被赋值,自然会先输出undefined。
解决方案
把异步回调改成Promise形式,用async/await控制执行顺序,确保所有需要的异步操作完成后再执行后续的日志代码:
1. 封装异步API为Promise
先把Chrome的回调式API包装成支持await的Promise:
// 封装chrome.storage.local.get const getStorage = (keys) => { return new Promise(resolve => { chrome.storage.local.get(keys, resolve); }); }; // 封装chrome.identity.getProfileUserInfo const getProfileUserInfo = () => { return new Promise(resolve => { chrome.identity.getProfileUserInfo(resolve); }); };
2. 修改handleLogin函数
用await等待异步操作完成,保证代码按预期顺序执行:
let tenant; const handleLogin = async () => { consoleLog('Logging in'); IP = await getPublicIP(); let uuid; // 等待获取uuid的操作完成 const storageResult = await getStorage(['uuid']); uuid = storageResult.uuid; consoleLog('uuid: ', uuid); consoleLog('tenant: ', tenant); // 检查用户信息 if (!tenant) { consoleLog('Checking User Profile'); const userInfo = await getProfileUserInfo(); if (userInfo.email !== "") { consoleLog('User is logged in browser', userInfo.email); if (!uuid) { uuid = userInfo.email; } // 合并storage.set操作,减少异步调用次数 await chrome.storage.local.set({ browser_auth_verified: true, email: uuid, uuid }); const emailDomain = getDomainWithoutTLD(userInfo.email); tenant = emailDomain; consoleLog('Domain is ', emailDomain); login(uuid, userInfo.email, userInfo.id); } } // 现在这两句会在所有异步操作完成后执行 consoleLog('Tenant ', tenant); consoleLog('Tenant ', tenant == null || tenant == undefined); };
额外优化说明
- 合并了多次
chrome.storage.local.set调用,减少异步操作的开销,提升性能。 - 如果需要确保
chrome.storage.local.set完全完成后再执行后续逻辑,可以同样把它封装成Promise并加上await,不过你的代码里后续没有依赖这个操作的结果,所以可选。
内容的提问来源于stack exchange,提问作者laskdjf
相关产品推荐
相关产品推荐

