I need to build an object that show 2 arrays. For it I call the first promise and then I use its result to call the second promise.
I want know if have some best way to resolve this problem.
The problem is described below.
/**
* DO NOT USE ASYNC/AWAIT
* Using the below two functions produce the following output
* {
* authors: ['bob', 'sally'],
* titles: ['Greeting the World', 'Hello World!']
* }
* */
const getBooks = () => {
return new Promise((resolve) => {
resolve([
{
bookId: 1,
author: "bob"
},
{
bookId: 2,
author: "sally"
}
]);
});
};
const getTitle = (bookId) => {
return new Promise((resolve, reject) => {
switch (bookId) {
case 1:
resolve({ title: "Greeting the World" });
break;
case 2:
resolve({ title: "Hello World!" });
break;
default:
reject(new Error("404 - book not found"));
}
});
};
let authors = {authors: [], titles: []}
getBooks()
.then(result => {
result.map(
t => {
authors.authors.push(t.author)
getTitle(t.bookId)
.then(result => {
authors.titles.push(result.title)
})
})
}).then(_ => console.log(authors))