Reputation: 31
Multiple fetch res render function , hey I am trying to perform and multiple res render function in ejs but my data is lost is their any fix
app.get("/" , function(req,res){
fetch(`${domain}/popular`)
.then(res => res.text())
.then(datap => {
res.render('home',{datap : JSON.parse(datap)});})
fetch(`${domain}/recent-release`)
.then(res => res.text())
.then(datar => {
res.render('home',{datar : JSON.parse(datar)});})
})
i want to make multiple fetch function but the datar is replacing datap
Upvotes: 1
Views: 140
Reputation: 169298
Convert the function to async
, await
for the two requests, render only when they're done. (I also took the liberty of using the asynchronous res.json()
parser instead of res.text()
+ JSON.parse
.)
app.get("/", async function(req, res) {
const res1 = await fetch(`${domain}/popular`);
const datap = await res1.json();
const res2 = await fetch(`${domain}/recent-release`);
const datar = await res2.json();
res.render("home", { datap, datar });
});
(A future optimization could be to do the two requests in parallel using Promise.all()
.)
Upvotes: 1