首页 > 解决方案 > JS 承诺:如何链接 `then` 调用?

问题描述

我正在尝试获取一些数据,重新处理对象格式并将其安全地保存在状态中。我的最后一个.then没有从第二个获得数据。我不明白为什么会这样。

fetch("http://myserver/switches")
    .then(response => response.json())
    .then(data => {
      a = data.map(item => {
        var obj = {}
        obj = {value: item.switch, label: item.switch}
        return obj
      })
      console.log(a)
    })
    .then(data => {
      console.log(data)
      this.setState({ switches: data})
      console.log(this.state.switches)
      })

控制台日志:

 >(5) [{…}, {…}, {…}, {…}, {…}]
 >undefined
 >undefined

标签: promise

解决方案


尝试在第二个 then() 中添加一个语句,return a 这将a作为最后一个 then() 的参数。

fetch("http://myserver/switches")
.then(response => response.json())
.then(data => {
  a = data.map(item => {
    var obj = {}
    obj = {value: item.switch, label: item.switch}
    return obj
  })
  console.log(a)
  return a;
})
.then(data => {
  console.log(data)
  this.setState({ switches: data})
  console.log(this.state.switches)
  })

推荐阅读