首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >响应调用API筛选出未定义的承诺

响应调用API筛选出未定义的承诺
EN

Stack Overflow用户
提问于 2017-08-01 20:58:09
回答 1查看 320关注 0票数 0

我正在试图找出如何在API调用上映射。

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

以下是两次失败的尝试

1:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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))

编辑添加了第三次尝试:

代码语言:javascript
运行
复制
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时会使用一个查询(从输入中检索),这将返回我希望从其中拒绝未定义对象的承诺。

邮递员的工作对象示例

代码语言:javascript
运行
复制
{
    "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"
        }
    ]
}

来自拒绝的示例

代码语言:javascript
运行
复制
{
    "books": {
        "error": "empty query",
        "items": []
    }
}

编辑:-

代码语言:javascript
运行
复制
BooksAPI.search(query)
    .then((searchResult) => {
      console.log(searchResult)

首先给我一个答复(第一毫秒)

代码语言:javascript
运行
复制
[]
  length: 0
   __proto__: Array(0)

后面跟着一个

代码语言:javascript
运行
复制
(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

希望能就如何进行提供一些意见。干杯!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-03 10:03:44

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

代码语言:javascript
运行
复制
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的形式返回。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45447602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档