1

我正在创建一个简单的图书搜索应用程序,我发出初始 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;
  };
4

1 回答 1

0

TLDR

在我看来,你需要返回promise(我的意思是需要返回axios

回答

我认为 promise 对象中没有返回值。当你async/awaitconst addHeight = data.map(async (book)=> {...})这个回调中使用时不能返回任何东西。所以当你返回 axios 时,你的 promise 可以得到正确的数据

例子

 addHeight = (data) => {
    const addHeight = data.map((book) => {
     return 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;
          } else {
            book["height"] = "0";
          }
          return book;
        });
    });
    return addHeight;
  };
于 2020-07-31T19:12:49.420 回答