【问题标题】:Nesting a fetch promise inside another promise (React)?在另一个 Promise 中嵌套一个 fetch Promise (React)?
【发布时间】:2020-02-02 08:00:51
【问题描述】:

我正在创建一个简单的 React Web 应用程序,它将使用 Reddit 的 api 显示 Reddit 内容。

handleLoad(event) {
    (() => {
        this.setState({
        isLoading: true
    });
    var newUrl = "https://www.reddit.com/r/" + this.state.search + ".json"
        return new Promise((resolve, reject) => {
            fetch(newUrl)
            .then((res) => {
                if(res.ok){
                    resolve(res.json())
                } else {
                    reject(res.status)
                }
            })
        }).then(data => {
            this.setState({
                info: data,
                isLoading: false,
                error: false
            })
        }).catch((message)=>{
            this.setState({
                isLoading: false,
                error: true
            })
        })
    })()
}

这段代码确实有效,但我想知道是不是我做得太多了?我希望能够捕获任何错误(在 subreddit 不存在或被阻止的情况下),以便我的应用不会崩溃。

【问题讨论】:

  • 去掉外层的Promise(promise wrapper)

标签: javascript reactjs fetch es6-promise


【解决方案1】:

以下内容应该足够了。

如果您的承诺成功,则返回一个新的 JSON 承诺并相应地设置状态。

如果不是,则抛出一个错误并在您已经在其中处理该错误的 setState 的 catch 块中。

handleLoad(event) {
  (() => {
    this.setState({
      isLoading: true
    });
    var newUrl = "https://www.reddit.com/r/" + this.state.search + ".json"

    fetch(newUrl)
      .then((res) => {
        if (res.ok) {
          return res.json()
        }
        throw new Error('failed')
      })
      .then(data => {
        this.setState({
          info: data,
          isLoading: false,
          error: false
        })
      }).catch((message) => {
        this.setState({
          isLoading: false,
          error: true
        })
      })
  })()
}

【讨论】:

    【解决方案2】:

    由于 fetch 已经返回一个 Promise,所以在另一个 .then() 块中处理响应,您不需要将其包装在另一个 Promise 中。

    幸福之路:

    1. 调用 API
    2. 将响应解析为 JSON
    3. 处理成功的响应

    不那么幸福的道路: 1.调用API 2.检查res,如果不ok,就用status报错 3.catch块会处理抛出的错误

    示例

    var newUrl = "https://www.reddit.com/r/emoji.json"
    
    fetch(newUrl)
      .then(res => {
        if(!res.ok) throw new Error(res.status);
      })
      .then((res) => res.json()
      ).then(data => {
        console.log(data) // handle success
      }).catch((error) => {
        console.log(error.message) // handle failure
      })

    【讨论】:

      猜你喜欢
      • 2017-10-11
      • 1970-01-01
      • 2023-03-31
      • 2017-07-31
      • 1970-01-01
      • 2019-10-21
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多