我花了很多时间尝试调试此问题,但这可能是由于我对async / await如何与TypeScript / JavaScript一起工作缺乏了解。我正在从一个返回诺言的函数中获取存储在浏览器存储中的项目,然后检查.length是否大于0。如果我对从GetReminders
返回的对象进行日志记录,那么我肯定可以看到其中确实有项目,但是为什么reminders.length == 0
是真的?
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);
}
}
编辑:代码就在那儿,我想从具有回调的函数中返回Promise的模式是像这样解决回调中的Promise。
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)
});
});
}