【问题标题】:React call API filter out undefined promisesReact 调用 API 过滤掉未定义的 Promise
【发布时间】:2017-08-03 18:03:44
【问题描述】:

我试图弄清楚如何映射 API 调用。

场景是调用一个返回承诺的 API。 这个承诺可能包括未定义的对象,我想跳过这些对象,只将工作对象添加到名为 `searchResult` 的状态中

这里有两次失败的尝试

1:

onSearch = (query) => {
    if(query){
    BooksAPI.search(query).then((searchResult) => {
      if(typeof searchResult !== 'undefined') {
        console.log(searchResult)
        searchResult.map((books) => {
          books.shelf = this.state.bookShelfMapping[books.id] ?
          this.state.bookShelfMapping[books.id] : 'none'
        })
        // Check if users changes searchResult
        if(this.state.searchResult !== searchResult) {
          this.setState({searchResult})

        }
      } else {
        continue
      }
    }).catch( e => console.log(e))
  }
}

2:

onSearch = (query) => {
    if(query){
    BooksAPI.search(query).then((searchResult) => {
      if (Array.isArray(searchResult)) {
        searchResult.map((books) => {
          books.shelf = this.state.bookShelfMapping[books.id] ?
          this.state.bookShelfMapping[books.id] : 'none'
        })
        // Check if users changes searchResult
        if(this.state.searchResult !== searchResult) {
          this.setState({searchResult})

        }
      } else {
        this.setState({searchResults: []})
      }
    }).catch( e => console.log(e))

编辑添加第三次尝试:

onSearch = debounce((query) => {
    console.log("In onSearch()")
    BooksAPI.search(query)
    .then((searchResult) => {
      console.log(searchResult)
      console.log("In onSearch() first .then")
      if(!Array.isArray(searchResult)) {
        throw new Error('Bad response')
      }
    })
    .then((searchResult) => {
      console.log("In onSearch() second .then")
      if (typeof searchResult !== 'undefined' && Array.isArray(searchResult)) {
        console.log("In onSearch() second .then if statement")
        searchResult.map((books) => {
          books.shelf = this.state.bookShelfMapping[books.id] ?
          this.state.bookShelfMapping[books.id] : 'none'
        })

        this.setState({searchResult})

      }
    })
    .catch( e => {
      console.log("in onSearch .catch")
      console.log(e)
    })
    console.log(this.state.searchResult)
  }, 300)

如上所示,BooksAPI 被调用一个查询(从输入中检索),这将返回我想要拒绝未定义对象的承诺。

邮递员的工作对象示例

{
    "books": [
        {
            "title": "Taijiquan Classics",
            "subtitle": "An Annotated Translation",
            "authors": [
                "Barbara Davis",
                "Weiming Chen"
            ],
            "publisher": "North Atlantic Books",
            "publishedDate": "2004",
            "description": "Along with Chinese art, medicine, and philosophy, taijiquan has left the confines of its original culture, and offers health, relaxation, and a method of self-defense to people around the globe. Using the early texts now known as The Taijiquan Classics which have served as a touchstone for t’ai chi practitioners for 150 years, this book explores the fundamental ideas and what they mean to practitioners, students, and scholars. It also incorporates newly discovered sources that address the history of taijiquan and newly translated commentaries by Chen Weiming.",
            "industryIdentifiers": [
                {
                    "type": "ISBN_10",
                    "identifier": "1556434316"
                },
                {
                    "type": "ISBN_13",
                    "identifier": "9781556434310"
                }
            ],
            "readingModes": {
                "text": false,
                "image": false
            },
            "pageCount": 212,
            "printType": "BOOK",
            "categories": [
                "Health & Fitness"
            ],
            "maturityRating": "NOT_MATURE",
            "allowAnonLogging": false,
            "contentVersion": "0.0.1.0.preview.0",
            "panelizationSummary": {
                "containsEpubBubbles": false,
                "containsImageBubbles": false
            },
            "imageLinks": {
                "smallThumbnail": "http://books.google.com/books/content?id=vOoexFHEKXgC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
                "thumbnail": "http://books.google.com/books/content?id=vOoexFHEKXgC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
            },
            "language": "en",
            "previewLink": "http://books.google.com/books?id=vOoexFHEKXgC&printsec=frontcover&dq=classics&hl=&cd=1&source=gbs_api",
            "infoLink": "http://books.google.com/books?id=vOoexFHEKXgC&dq=classics&hl=&source=gbs_api",
            "canonicalVolumeLink": "https://books.google.com/books/about/Taijiquan_Classics.html?hl=&id=vOoexFHEKXgC",
            "id": "vOoexFHEKXgC",
            "shelf": "none"
        }
    ]
}

拒绝示例

{
    "books": {
        "error": "empty query",
        "items": []
    }
}

编辑:-----

BooksAPI.search(query)
    .then((searchResult) => {
      console.log(searchResult)

首先给我一个响应(第一毫秒)

[]
  length: 0
   __proto__: Array(0)

后跟一个

(20) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0
:
Object
allowAnonLogging
:
false
authors
:
Array(2)
averageRating
:
4
canonicalVolumeLink
:
"https://books.google.com/books/about/Best_Android_Apps.html?hl=&id=bUybAgAAQBAJ"
categories
:
Array(1)
contentVersion
:
"preview-1.0.0"
description
:
"Contains descriptions of over two hundred recommended applications and games for android/mobile devices, including apps for business, communication, lifestyle, entertainment, utility/tool, and reference."
id
:
"bUybAgAAQBAJ"
imageLinks
:
Object
industryIdentifiers
:
Array(2)
infoLink
:
"http://books.google.com/books?id=bUybAgAAQBAJ&dq=android&hl=&source=gbs_api"
language
:
"en"
maturityRating
:
"NOT_MATURE"
pageCount
:
240
previewLink
:
"http://books.google.com/books?id=bUybAgAAQBAJ&dq=android&hl=&cd=1&source=gbs_api"
printType
:
"BOOK"
publishedDate
:
"2010-04-27"
publisher
:
""O'Reilly Media, Inc.""
ratingsCount
:
3
readingModes
:
Object
shelf
:
"currentlyReading"
subtitle
:
"The Guide for Discriminating Downloaders"
title
:
"Best Android Apps"
__proto__
:
Object

不胜感激有关如何进行的一些意见。 干杯!

【问题讨论】:

  • 您的第二种方法看起来不错,但我认为您应该检查 searchResult && Array.isArray(searchResult.books)
  • 嗨@Akhil 我现在试过了。不幸的是,这根本没有给我任何结果
  • 你能在if之前console.log(searchResult);吗?根据您的回复searchResultobject 而不是array,您需要先执行searchResult.books
  • 是的,我可以在BooksAPIif statment 之间使用console.log(searchResult),但是当在if 之后尝试console.log(searchResult.books) 时返回undefined
  • 如果在上下文中更容易看到它,存储库位于此处link

标签: javascript reactjs promise es6-promise


【解决方案1】:

为此,我最终得到了这样的解决方案。

onSearch = debounce((query) => {

      BooksAPI.search(query).then((searchResults) => {
        if (!searchResults || searchResults.error){
          this.setState({searchResult : []})
          return searchResults
        } else if (Array.isArray(searchResults)) {

            searchResults.map((book) => {
              book.shelf = this.state.bookShelfMapping[book.id] ?
              this.state.bookShelfMapping[book.id] : 'none'
              return searchResults

            })

            if (this.state.searchResults !== searchResults) {

              this.setState({searchResult : searchResults})

            }
        } })
        .catch(e => console.log(e))
    }, 300)

我之前错过的一件事是 searchResult 可以同时返回 undefined.error

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 2017-04-02
    • 1970-01-01
    • 2021-06-19
    • 2017-12-14
    • 2019-09-15
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多