Home > Back-end >  How to wait for one request to finish, till the other can get executed on Express/Node?
How to wait for one request to finish, till the other can get executed on Express/Node?

Time:06-10

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

CodePudding user response:

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))

            })
      });

    }

CodePudding user response:

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);
})
  • Related