startup storage sync is now a promise

This commit is contained in:
Ilya Ig. Petrov 2016-01-26 20:50:25 +05:00
parent 9420177df2
commit 278aaad865

View File

@ -60,7 +60,7 @@ window.antiCensorRu = {
if (Object.getOwnPropertyDescriptor(this, key).writable && typeof(this[key]) !== 'function') if (Object.getOwnPropertyDescriptor(this, key).writable && typeof(this[key]) !== 'function')
onlySettable[key] = this[key] onlySettable[key] = this[key]
return chrome.storage.local.set(onlySettable, cb); return chrome.storage.local.set(onlySettable, () => cb(chrome.runtime.lastError, onlySettable) );
}, },
pullFromStorage(cb) { pullFromStorage(cb) {
@ -68,8 +68,9 @@ window.antiCensorRu = {
for(var key of Object.keys(storage)) for(var key of Object.keys(storage))
this[key] = storage[key]; this[key] = storage[key];
console.log('Pulled from storage, any callback?', !!cb);
if (cb) if (cb)
cb(storage); cb(chrome.runtime.lastError, storage);
}); });
}, },
@ -127,46 +128,42 @@ window.antiCensorRu = {
}; };
window.ifPulled = false; // ON EACH LAUNCH OF EXTENSION
window.onPulledFuns = [];
function pullFinished() { window.storageSyncedPromise = new Promise(
window.onPulledFuns.map( fun => fun() ); (resolve, reject) => window.antiCensorRu.pullFromStorage(
window.ifPulled = true; (err, res) => err ? reject(err) : resolve(res)
} )
function execAfterPulled(fun) { );
if (window.ifPulled)
fun(); window.storageSyncedPromise.then(
else storage => {
window.onPulledFuns.push( fun ); chrome.alarms.onAlarm.addListener(
} alarm => {
if (alarm.name === window.antiCensorRu._periodicUpdateAlarmReason) {
console.log('Periodic update triggered:', new Date());
window.antiCensorRu.syncWithPacProvider();
}
}
);
console.log('Installed alarm listener.');
}
);
chrome.runtime.onInstalled.addListener( details => { chrome.runtime.onInstalled.addListener( details => {
console.log('Installing, reason:', details.reason); console.log('Installing, reason:', details.reason);
switch(details.reason) { window.storageSyncedPromise.then(
case 'update': storage => {
return execAfterPulled( () => window.antiCensorRu.installPac() ); switch(details.reason) {
case 'install': case 'update':
return execAfterPulled( () => { window.antiCensorRu.installPac();
window.antiCensorRu.ifNotInstalled = true; break;
chrome.runtime.openOptionsPage(); case 'install':
} ); window.antiCensorRu.ifNotInstalled = true;
} chrome.runtime.openOptionsPage();
});
window.antiCensorRu.pullFromStorage( () => {
console.log('Pulled from storage.');
chrome.alarms.onAlarm.addListener(
alarm => {
if (alarm.name === window.antiCensorRu._periodicUpdateAlarmReason) {
console.log('Periodic update triggered:', new Date());
window.antiCensorRu.syncWithPacProvider();
} }
} }
); )
console.log('Installed alarm listener.');
return pullFinished();
}); });
// PRIVATE // PRIVATE