【发布时间】:2019-01-21 22:20:13
【问题描述】:
我输入的数据格式如下:
[ [4, 1, 2], [2, 5] ]
我想对数组中的每个数字进行 api 调用,并输出如下:
[ [response_4, response_1, response_2], [response_2, response_5] ]
我已经被这个逻辑困住了两天——我无法正确格式化我的返回数组。它反而返回:
[ response_4, response_1, response _2, response_2, response_5 ]
我知道我在使用 Promise/async 方面做错了,而且我知道我需要在某个时候将 temp 重置为 length = 0,但是每次添加它时,它都会简单地返回 []作为我的输出。有什么建议/帮助吗?
const getNumData = (data) => {
let temp = []
return new Promise((resolve, reject) => {
data.forEach((outerArray) => {
return new Promise((resolve, reject) => {
outerArray.forEach((number) => {
return fetch(`http://127.0.0.1:8000/api/number?id=${number}`, {method: 'GET',})
.then((response) => response.json())
.then((responseJson) => {
temp = this.state.seqDone.concat(responseJson[0]);
this.setState({
seqDone: temp
})
console.log(temp)
})
})
if (this.state.seqDone) {
console.log(this.state.seqDone)
resolve(this.state.seqDone);
} else {
reject(Error('Sequences not found'));
}
})
});
if (this.state.seqDone) {
console.log(this.state.seqDone)
resolve(this.state.seqDone);
} else {
reject(Error('Sequences not found'));
}
})
}
【问题讨论】:
标签: javascript react-native asynchronous foreach