0

I have input data that is formatted as such:

[ [4, 1, 2], [2, 5] ]

I want to make an api call for each of the numbers in the array, and have output as such:

[ [response_4, response_1, response_2], [response_2, response_5] ]

I've been stuck on this logic for two days-- I can't get my return array formatted correctly. It instead returns:

[ response_4, response_1, response _2, response_2, response_5 ]

I know I'm doing something wrong in terms of using promises/async, and also I know I need to reset temp to length = 0 at some point, but every time I add that in, it will simply return [] as my output. Any advice/help?

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 Answers 2

2

You can do it in this way

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 accepts array of functions as arguments, thoses functions will be executed asynchronously. In your case you just have to use it recursively

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help. I ended up doing something similar
Glad to hear you found a solution. Do you think that this can be the right answer ? Can you mark it as the right one if it does please ?
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))
  })

  }

1 Comment

This is the solution that I ended up going with

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.