Reputation: 261
I write a simple function using hrome.storage.local.get
chrome.storage.local.get(['valueInput'], (result) => {
if (typeof result.valueInput !== 'undefined') {
let selectorInput = document.querySelectorAll('input');
result.valueInput.forEach((item, index) => selectorInput[index].value = item);
}
});
And i splice this code to independent function
function getFromeStorage(value) {
let arr = [];
chrome.storage.local.get(value, (result) => {
if (typeof result.valueInput !== 'undefined') {
result.valueInput.forEach((item, i) => arr[i] = item);
}
});
return arr;
\\ Array(18)[0: "3" 1: "1" 2: "1" 3: "1" 4: "1" 5: "1" 6: "1" 7: "1" 8: "1" 9: "1" 10: "1" 11: "1" 12: "1" 13: "1" 14: "1" 15: "1" 16: "1" 17: "1"]
}
But when i splice this function this function wont work
let selectorInput = document.querySelectorAll('input');
let valueInput = getFromeStorage("valueInput");
valueInput.forEach((item, index) => selectorInput[index].value = item);
HTML
<tr>
<td class="center-align">Administrowanie systemami operacyjnymi</td>
<td class="center-align row">
<input type="number" class="input-default-weight" min="1" max="20" value="1">
<i id="hint-default-weight" class="material-icons md-dark center-vertically tooltipped hint" data-position="top" data-delay="250" data-tooltip="Ilość lekcji w tygodniu" data-tooltip-id="1b1400b4-3270-0b0c-da17-8540ce6f2408">info_outline</i></td>
<td class="center-align">5</td>
<td class="center-align yearPresent">86%</td>
</tr>
This is the same code but i only splice my main code to function and i call this in my code. How can i fix this?
Upvotes: 0
Views: 41
Reputation: 5591
It looks like you're returning the arr
variable before the callback has been called so it's always returning an empty array.
function getFromeStorage(value) {
let arr = [];
chrome.storage.local.get(value, (result) => {
// This function won't fill 'arr' until later
if (typeof result.valueInput !== 'undefined') {
result.valueInput.forEach((item, i) => arr[i] = item);
}
});
// This empty 'arr' gets returned too early
return arr;
Since chrome.storage.local.get
is asynchronous your function accessing it must deal with that. One way is to add a callback or Promise to your function. To keep it simple here's how it would look with a callback:
function getFromeStorage(value, callback) {
chrome.storage.local.get(value, (result) => {
const arr = [];
if (typeof result.valueInput !== 'undefined') {
result.valueInput.forEach((item, i) => arr[i] = item);
}
callback(arr);
});
}
You would then have to change how you use the function to wait for the callback
to be called like this:
let selectorInput = document.querySelectorAll('input');
let valueInput = getFromeStorage("valueInput", (valueInput) =>{
valueInput.forEach((item, index) => selectorInput[index].value = item);
});
Upvotes: 2