-2

I'm trying to make a request for each item captured in the MAP, but I would like to wait for the response before going to the other object within the MAP. At the moment my code is making all the requests at the same time, which ends up crashing the Backend.

    function RequestComputers (Computers) {
        Computers.map((e) => {
            Details(e, data.region, data.apitoken).then(data => {  
                if(data)
                setContent2((array) => [...array, data[0]])} ).catch(error => console.log(error))
            
    
        })
    
}
const Details = async (Computer, region, token) => {
    try {
        const test = {'region': region, 'apitoken': token, 'product': '1', 'computer': Computer}
        const response = await fetch('url', {
        method: 'POST',
        headers: {
           'Content-Type': 'application/json'
           },
           body: JSON.stringify(test)
        }
        )
        const data = await response.json()
        return data
       } catch(error) {
          console.log(error)
         } 
    }

I need to wait for the fetch response and only then make another fetch request

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    `but I would like to wait for the response before going to the other object within the MAP` If that's what you want, then `.map` is not the right tool for the job. Will you accept answers that don't use `.map`? – Nicholas Tower Dec 30 '22 at 18:11

2 Answers2

1

You can use a simple for loop:

async function RequestComputers (Computers) {

    for ( const computer of Computers ) {

      try {
        const data = await Details(computer, data.region, data.apitoken);
        if ( data ) {
            setContent2((array) => [...array, data[0]]);
        }
      } catch(error){
          console.log(error);
      }

    }

}

Reference

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
-1

I think you could use .forEach and await Details:

async function RequestComputers (Computers) {
    
    Computer.forEach(async(computer) => {
      try {
        const data = await Details(computer, data.region, data.apitoken);
        if ( data ) {
            setContent2((array) => [...array, data[0]]);
        }
      } catch(error){
          console.log(error);
      }
    })
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 30 '22 at 19:50
  • This code will result in the following Error: Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules – Kostas Minaidis Dec 31 '22 at 16:48