-2
const books_div = document.querySelector('.root');


const showAllBooks = async () => {
    console.log('running');

    try {

        const { data: { books } } = await axios.get('api/v1/home/all');
        console.log(books);
        if (books.length < 1) {
            books_div.innerHTML = '<h5 class="empty-list">No Books in your Directory</h5>'
            return
        }
        const allBooks = books.map(async (book) => {
            const { name, authorName, _id: bookID } = book;

            var readingStatus = 'Start Reading';
            try {
                const { data: { books: ongoingBooks } } = await axios.get(`api/v1/home/ongoing/${name}`);
                if (ongoingBooks.length !== 0) {
                    readingStatus = 'Ongoing';
                }
            } catch (error) {
                console.log(error);
            }

            return (
                `<div class="single-book">
                <div class="name-author-div">
                <h4>${name}</h4>
            <p class="author-name">${authorName}</p>
            </div>
            
            <div class="icon-div">
            <a class="favourite-btn" data-id="${bookID}"><img src="./icons/fav.svg" alt="star-icon"></a>
            <a class="delete-btn" data-id="${bookID}"><img src="./icons/dlt.svg" alt="bin-icon"></a>
            </div>
    
            <button class="btn">${readingStatus}</button>
            </div>`
            );
        }).join('');

        books_div.innerHTML = allBooks;
        console.log(`here is the book div ${books_div}`);

    } catch (error) {
        console.log(error);
    }
}



showAllBooks();

I am trying to make a book directory in which there are four directories which are

  1. All Directory
  2. Ongoing Directory
  3. Favorite Directory
  4. Completed Directory There is a button on which I want to display "ongoing" if that book is in "ongoing directory" and "start reading" if it is not there in the "ongoing directory". What I am doing in order to achieve this is for every book I am checking whether that book is in "ongoing directory" or not and then changing the text based on that. I am making an API call inside an API call but it is returning [promise object] instead of data. Please Help me find out what I am doing wrong.enter image description here

1 Answers1

0

Seems that your problem comes from your books.map which is executed asynchronously due to the fetch operation but your code which is displaying the results is called just after without waiting.

You should adapt a little bit by using a Promise.all:

await Promise.all(books.map(async (book) => {
  // ...
});
books_div.innerHTML = allBooks;
JStw
  • 1,155
  • 11
  • 20