首页 > 解决方案 > 在另一个 fetch 中使用从 promise 返回的数据不起作用

问题描述

我有一个handleSubmit 函数,我添加了两个post 请求。

但是,其中一个发布请求依赖于从第一个发布请求返回的数据。我试图通过将其设置为 var 来访问这些数据,但在第二次提取中似乎无法访问它。不确定我的语法是否错误..有什么想法吗?

我相信这应该可行,但我不确定我哪里出错了。谢谢!

handleSubmit = () => {
  fetch('http://localhost:3000/resources', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json'
      },
      body: JSON.stringify({
        name: this.state.name,
        description: this.state.description,
        link: this.state.link,
        topic_id: this.state.topic_id
      })
    })
    .then(res => res.json())
    .then(data => {
      this.props.addResource(data)
      var dataId = data.id;
    })

  return fetch('http://localhost:3000/user_resources', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json'
      },
      body: JSON.stringify({
        resource_id: dataId,
        user_id: this.props.users.id
      })
    })
    .then(res => res.json())
    .then(data => {
      this.props.addUserResource(data)
    })

  this.props.navigation.goBack()
}

标签: react-nativepromisereact-reduxfetch

解决方案


有2个问题:

  1. return一些代码,然后尝试运行其他东西。您的this.props.navigation.goBack()语句将永远无法到达,因为函数在到达return. 不过,这不是您的主要问题。
  2. fetch是异步的。这意味着函数 handleSubmit 将读取前两个语句(“获取资源”和“返回获取用户资源”),然后当每个获取完成时,它们将运行它们的.then()函数。

这意味着您dataId将未定义,您需要等待第一次提取完成并执行第二次提取。

handleSubmit = () => {
  fetch('http://localhost:3000/resources', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json'
      },
      body: JSON.stringify({
        name: this.state.name,
        description: this.state.description,
        link: this.state.link,
        topic_id: this.state.topic_id
      })
    })
    .then(res => res.json())
    .then(data => {
      this.props.addResource(data)

      return fetch('http://localhost:3000/user_resources', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json'
        },
        body: JSON.stringify({
          resource_id: data.id,
          user_id: this.props.users.id
        })
      })
    })
    .then(res => res.json())
    .then(data => {
      this.props.addUserResource(data)
    })

  this.props.navigation.goBack()
}

推荐阅读