promise - 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
解决方案
尝试在第二个 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)
})
推荐阅读
- information-retrieval - 精确召回数据集
- symfony - Symfony 3 原则中的多重坚持
- php - 使用 LEFT JOIN 对不同表中的值求和
- java - 模拟 Jersey 代理客户端 Dropwizard
- matlab - MATLAB:使用逻辑索引将矩阵中的值替换为其值除以 2?
- php - 在 Woocommerce 3 中检查最近未完成订单的状态
- c# - 时间:2019-04-10 标签:c#sort HTTP request headers
- c++ - 使用睡眠控制循环时间
- python - 使用 keras.utils.Sequence 时,keras predict_generator 正在改组其输出
- python - MLP 无法学习线性方程组