From my understanding, a promise's then method will only execute once a promise has been fulfilled.
However, in displayAdParams below, the second then block is executing even when getTabParamsFromStorage has not returned a promise/not fulfilled. This causes 'params' in the second then block to be undefined.
function displayAdParams() {
getTabId().then(tabId => {
return getTabParamsFromStorage(tabId);
}).then(params => {
console.log('b', params);
updatePopupWithStandardParams(params.shift());
});
}
function getTabId() {
return new Promise((resolve, reject) => {
let queryInfo = {active: true, currentWindow: true};
chrome.tabs.query(queryInfo, tabs => {
resolve(String(tabs[0].id));
});
});
}
This version of getTabParamsFromStorage doesn't work (Using Promise.resolve)
// This doesn't work
function getTabParamsFromStorage(tabId) {
chrome.storage.local.get(tabId, items => {
console.log('a', items[tabId]);
return Promise.resolve(items[tabId]);
});
}
/* output
popup.js:7 b undefined
TypeError: Cannot read property 'shift' of undefined
at getTabId.then.catch.then.params (popup.js:8)
popup.js:47 a Array(7)
*/
This version of getTabParamsFromStorage works fine (Using new Promise)
// This works
function getTabParamsFromStorage(tabId) {
return new Promise((resolve, reject) => {
chrome.storage.local.get(tabId, items => {
console.log('a', items[tabId]);
resolve(items[tabId]);
});
});
}
Why is this happening and what can I do to get the first version of getTabParamsFromStorage working?