使用 async/await 仅在数据库获取功能后呈现信息

Using async/await to render information only after db fetching function

所以我有一个数据库获取功能,它是从 firebase 获取数据,这在您最初打开页面时需要一些时间,(数据仅在 700 毫秒后完成获取),我正在尝试实现一种方法让我仅在获取了所有数据后才使用 async/await 和承诺从数据库中呈现初始信息,但我无法正确实现它。

该项目是一个小库列表,getFromDB() 从 firebase 获取所有信息到一个数组(与本地用户同步数据库),而 render() 只是将信息呈现到页面中整洁 table 格式

// Get all books from the FirebaseDB and synchs with myLibrary Array
function getFromDB() {
    return new Promise((resolve, reject) => {
        myLibrary.length = 0; // clears original stored array to get all books again
        firebaseRef.on("value", function (data) {
            data.forEach((book) => {
                //gets each book from firebase creates new book Object to array in the correct order(chronologically)
                property = book.val();
                let addedBook = new Book(
                    property.title,
                    property.author,
                    property.pages,
                    property.read,
                    book.key
                );
                myLibrary.push(addedBook);
            });
        });
        resolve(true); // resolve
    });
}

async function initialRender() {
    await getFromDB();
    render();
}

initialRender();

仍然没有呈现信息,因为 render() 函数 运行s 在任何信息完成获取之前。如果我之后在控制台上手动 运行 render(),一切都会正确呈现,这意味着 await 或 promise 没有按预期工作。

尝试将 resolve(true); 调用移动到 firebaseRef.on 函数的末尾。 现在发生的事情是,因为 firebaseRef.on 是一个 async 函数,而 resolve 是在这个函数之后而不是在它里面写的,resolve(true); 运行 一旦 getFromDB 是 运行。

// Get all books from the FirebaseDB and synchs with myLibrary Array
function getFromDB() {
    return new Promise((resolve, reject) => {
        myLibrary.length = 0; // clears original stored array to get all books again
        firebaseRef.on("value", function (data) {
            data.forEach((book) => {
                //gets each book from firebase creates new book Object to array in the correct order(chronologically)
                property = book.val();
                let addedBook = new Book(
                    property.title,
                    property.author,
                    property.pages,
                    property.read,
                    book.key
                );
                myLibrary.push(addedBook);
            });
            // resolve moved inside
            resolve(true);
             ^^^^^^^^^^^^
        });
         
    });
}

async function initialRender() {
    await getFromDB();
    render();
}