This code essentially gets some data from an api, and puts it in two arrays which I then render on a page using a rendering engine. It works, but I am wondering if there is a different approach to this that is better (because the first await call will have to complete before the second one does - maybe with Promise.all - but then how do I pass the arrays in to render? Most of the code examples I've seen directly return from Promise.all [return await Promise.all(etc)])
app.get('/', async (req, res) => {
const fic = [];
const non = [];
await getBooks(fic, API.URL_HARDCOVER_FICTION);
await getBooks(non, API.URL_HARDCOVER_NONFICTION);
res.render('layout', {results: {fic: fic, non: non}});
});
const getBooks = async (array, url) => {
await axios.get(url + "?api-key=" + API.Key)
.then( async res => {
const list = await res.data.results.books;
list.forEach( book => {
array.push(new Book(
book.primary_isbn13,
book.title,
book.author));
})
})
.catch(error => {
console.error(error);
});
return array;
}
getBooksmethod not to take an array as first param, but simply return one, you can then do:const [fic, non] = await Promise.all([getBooks(API.URL...), getBooks(API.URL...)])and keep yourrendercall as-is