I am passing an object containing async functions to the .ejs file
const express = require('express')
const app = express()
const PORT = process.env.PORT || 3000
const functions = require('./functions.js')
app.set('view-engine', 'ejs')
app.listen(PORT, () => {
console.log('listening on 3000', new Date())
})
app.get('/', (req, res) => {
res.render('dashboard.ejs', { functions })
})
the function console logs the data and also returns it
const getPrice = async (coin) => {
let data = await CoinGeckoClient.coins.fetch(coin);
console.log(coin, "GBP", data.data.market_data.current_price.gbp)
console.log(data.data.market_data.price_change_percentage_24h, '% / 24 hours')
return `
${coin} "GBP" ${data.data.market_data.current_price.gbp}
${data.data.market_data.price_change_percentage_24h}% / 24 hours')
`
};
I want to render the returned data in the .ejs file. Im trying this
<body>
<p>
<%= functions.getPrice('ethereum') %>
</p>
</body>
the console log is successful when I refresh the browser
ethereum GBP 3141.5
3.00725 % / 24 hours
so the function is being called, but the data is not rendered to the screen.
I instead get [object Promise].
I feel like this is an async issue but not sure how/if I can get the ejs to await the returning data. Am I structuring this wrongly?
Any help gratefully appreciated!
CodePudding user response:
You can call your function in your JS file then pass the result to the EJS file:
app.get('/', async(req, res) => {
res.render('dashboard.ejs', { price: await functions.getPrice('ethereum')})
})
Then in your EJS:
<body>
<p>
<%= price %>
</p>
</body>