嵌套的forEach循环中的异步代码-本机响应

时间:2019-01-21 22:20:14

标签: javascript react-native asynchronous foreach

我输入的数据格式如下:

[ [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'));
    }
  })
}

2 个答案:

答案 0 :(得分:2)

您可以通过这种方式完成

const nestedPromise = async (items = []) => {
  return await Promise.all(
    items.map(async item => {
      if (Array.isArray(item) && item.length) {
        return await nestedPromise(item)
      }
      // return await call to your function
      return 'response-' + item
    })
  )
}

const items = [ [4, 1, 2], [2, 5] ]
nestedPromise(items).then(results => {
  console.log(results)
})

Promise.all接受函数数组作为参数,这些函数将异步执行。在您的情况下,您只需要递归使用

答案 1 :(得分:0)

  fetchData = (item) => {
    return fetch(`http://127.0.0.1:8000/api/pose?id=${item}`)
    .then (response => response.json())
  }

  constructArray = (items) => {
    Promise.all(items.map(nestedArray => {
    return Promise.all(nestedArray.map(this.fetchData))
    }
  ))
  .then((results) => {
    console.log(JSON.stringify(results))
  })

  }