Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

354
Vistas
How to wait for one request to finish, till the other can get executed on Express/Node?

I have a task which requires me to fetch data from a third party api(itunes) to search for content that that the third-party API provides. The third party API will be handled by the backend(Express and Node). Now, I want when I click a button(from react), to send a POST request first(using fetch), WAIT till the POST request till is done, then actually fetch the data(Execute the GET request)...

In other words: I want to make the second fetch method(get request), wait till the first fetch method(post request) is done executing/posting data. Then only can the get request be executed.

Link to JS code(React):

 async function postReq() {
      return await fetch('http://localhost:3001/', {
        method: "POST",
        headers:{ "Content-Type": "application/json" },
        body: JSON.stringify(userData)
      })
    }

 const fetchData = (e) =>{
      e.preventDefault();
      postReq();
      fetch('http://localhost:3001/api')
      .then((response)=> response.json())
      .then((data)=>{
        //console.log(data)
        sessionStorage.setItem(`${mediaType}`, JSON.stringify(data))
      
      })
    }

Link to JS code(Express/Node):

app.post('/', (req, res, next)=>{
    //console.log("hii", req.body.search)
    fetch(`https://itunes.apple.com/search?term=${req.body.search}&entity=${req.body.mediaType}&limit=8`).then(
        (response)=> response.json()
    ).then(
        (data)=>{
            console.log(data)
            fs.writeFile("data.json", JSON.stringify(data), (err)=>{
                if(err) throw err
            })
        }
    )
})

//when server receives GET request we want to server the data that was fetched,back to the user
app.get('/api', (req, res, next)=>{
    fs.readFile("data.json", (err, data)=>{
        if(err) throw err;
        //console.log(JSON.parse(data))
        res.json(JSON.parse(data));
    })
})
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can await for post request to get completed and then call GET api.

async function postReq() {
      return await fetch('http://localhost:3001/', {
        method: "POST",
        headers:{ "Content-Type": "application/json" },
        body: JSON.stringify(userData)
      })
    }

 const fetchData = (e) =>{
      e.preventDefault();
      postReq().then(data=>{
            fetch('http://localhost:3001/api')
            .then((response)=> response.json())
            .then((data)=>{
              //console.log(data)
              sessionStorage.setItem(`${mediaType}`, JSON.stringify(data))

            })
      });

    }

about 4 years ago · Juan Pablo Isaza Denunciar

0

app.post('/', async (req, res, next)=>{
    const data = await fetch(`https://itunes.apple.com/search?term=${req.body.search}&entity=${req.body.mediaType}&limit=8`);
    await fs.writeFile("data.json", JSON.stringify(data));
    const updatedFile = fs.readFile('data.json');
    res.json(updatedFile); // it will respond to your POST request with updated 
file.
    // res.redirect('/api') /* Or you can redirect to a certain route after POST method */    
})

app.get('/api', async (req, res, next)=>{
    const file = await fs.readFile("data.json");
    res.json(file);
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda