I've spent a considerable amount of time trying to debug this issue but it might stem from my lack of knowledge of how async/await works with TypeScript/JavaScript. I'm fetching items stored in browser storage from a function that returns a promise and then I check to see if the .length is > 0 or not. If I do a log of the object returned from GetReminders
then I can see there are definitely items in there but then why is reminders.length == 0
true?
export class ViewTrialsView {
static async render() {
let trialManager : TrialReminderManager = new TrialReminderManager();
let spinner = document.getElementById("spinner");
spinner.classList.add("is-active");
let remindersContainer = document.getElementById("reminders_container");
console.log("Rendering trials list markup...");
const reminders = await trialManager.GetReminders();
console.log(reminders);
spinner.classList.remove("is-active");
if (reminders.length == 0) {
remindersContainer.innerText = "No reminders found.";
return;
}
const markup =
`
<ul class="mdl-list">
${reminders.map(((reminder, index) => `
<li class="mdl-list__item mdl-list__item--two-line">
<span class="mdl-list__item-primary-content">
<span>${reminder.Name}</span>
<span class="mdl-list__item-sub-title">${reminder.ExpirationDate}</span>
</span>
<span class="mdl-list__item-secondary-content">
<a class="mdl-list__item-secondary-action href="#" id='${reminder.Id.toString()}'>
<i class="material-icons">cancel</i>
</a>
</span>
</li>
`))}
`;
remindersContainer.innerHTML = markup;
}
}
export class TrialReminderManager {
public AddReminder(trial : Trial) : void {
var key = trial.Id.toString();
window.browser.storage.sync.set({[key] : trial}, () => {
console.log(`Added new trial ${trial} with id ${trial.Id.toString()}.`);
})
}
public async GetReminders() : Promise<Array<Trial>> {
console.log("Getting reminders from browser storage.");
let reminders = new Array<Trial>();
window.browser.storage.sync.get(null, (items) => {
Object.keys(items).forEach(
reminder => reminders.push(items[reminder]));
});
return Promise.resolve(reminders);
}
}
Edit: The code was almost there, I suppose the pattern for returning a Promise from a function that has a callback is to resolve the promise inside the callback like so.
public async GetReminders() : Promise<Array<Trial>> {
return new Promise<Array<Trial>>((resolve, reject) => {
console.log("Getting reminders from browser storage.");
let reminders = new Array<Trial>();
window.browser.storage.sync.get(null, (items) => {
Object.keys(items).forEach(
reminder => reminders.push(items[reminder]));
resolve(reminders)
});
});
}