'Who to Render Multiple fetch function in ejs
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
Solution 1:[1]
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().)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AKX |
