我正在创建一个简单的图书搜索应用程序,我发出初始 api 请求以获取一组图书对象,然后我需要对每本书发出 api 请求以获取尺寸。当我console.log
最初的书籍数组时,书籍对象已添加attribute('height')
,但我相信这是因为在我进行 api 调用后数组已更新。然后,当我console.log
在进行单独的 api 调用之后的数组时,我得到了一系列的承诺。最后当我Promise.all()
的一连串诺言他们都回来了undefined
。我一直在使用 async/await 并希望您能提供任何提示或反馈,以帮助我弄清楚如何能够返回我在单个 api 中添加的“height”属性的书籍数组来电。
searchBook = (event) => {
event.preventDefault();
axios
.get(
"https://www.googleapis.com/books/v1/volumes?q=" +
this.state.searchField +
"&key=" +
this.state.apiKey
)
.then((data) => {
//fill in missing attributes
const cleanData = this.cleanData(data.data.items);
//filter books for specific author
const filterAuthor = this.filterAuthor(cleanData);
//add height attribute to book
const addHeight = this.addHeight(filterAuthor);
console.log(filterAuthor); //returns array of book objects
console.log(addHeight); //returns array of promises
Promise.all(addHeight).then((data) => {
console.log(data); //returns array of undefined
});
//this.setState({ books: addHeight });
});
};
//add 'height' attribute to book objects
addHeight = (data) => {
const addHeight = data.map(async (book) => {
await axios
.get(
"https://www.googleapis.com/books/v1/volumes/" +
book.id +
"?key=" +
this.state.apiKey
)
.then((data) => {
if (data.data.volumeInfo?.dimensions) {
book["height"] =
data.data.volumeInfo.dimensions.height.split(" ")[0] / 2.54; //convert cm to in
} else {
book["height"] = "0";
}
return book;
});
});
return addHeight;
};