【问题标题】:using data returned from promise in another fetch not working在另一个 fetch 中使用从 promise 返回的数据不起作用
【发布时间】:2020-12-03 10:59:38
【问题描述】:

我有一个 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-native promise react-redux fetch


    【解决方案1】:

    有两个问题:

    1. return 一些代码,然后尝试运行其他东西。您的this.props.navigation.goBack() 语句将永远无法到达,因为函数在到达return 时结束。不过,这不是您的主要问题。
    2. fetch 是异步的。这意味着函数 handleSubmit 将读取前两个语句(“fetch resources”和“return fetch user_resources”),然后当每个 fetch 完成时,它们将运行 .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()
    }
    

    【讨论】:

    • @sofiat123 你试过我写的吗?
    猜你喜欢
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2017-09-05
    • 2019-09-17
    相关资源
    最近更新 更多