0

I have a function that returns a value from an API. However, when I use the function within an EJS template, it returns a promise rather than the data. When I console.log (data), it shows the actual data I'm looking for.

Helper

const axios = require("axios");

    const getBrokerName = async (id) => {
        API_BROKERS_URL = `${process.env.API_URL}/api/v1/brokers/?`;

        const params = new URLSearchParams({
            id:id,
            key: process.env.API_KEY,
        });
        
        try {
            const {data} = await axios.get(`${API_BROKERS_URL}${params}`);
            console.log(data.name)
            return data.name
            
        } catch (error) {
            console.log(err)
        }
    }

module.exports = { getBrokerName }

EJS file

<%= helper.getBrokerName(account.broker_id) %>

Result

[object Promise]

What did I miss here?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    [Why is my asynchronous function returning Promise { } instead of a value?](https://stackoverflow.com/q/38884522) | [Async function returning promise, instead of value](https://stackoverflow.com/q/51338277) | [How to access the value of a promise?](https://stackoverflow.com/q/29516390) | [What are asynchronous functions in JavaScript? What is "async" and "await" in JavaScript?](https://stackoverflow.com/q/62196932) – VLAZ Sep 28 '22 at 17:44
  • Could you please reformat my function with the correct way ? – Richard Branson Sep 28 '22 at 17:46

1 Answers1

1

You are calling an async function in EJS. Async functions always return a promise.

For that to work with EJS, you need to set the async parameter when calling the res.render function in your API.

Look at this answer for more details: https://stackoverflow.com/a/60824780/7025986

TL;DR

In your server API:

const ejs = require('ejs');
const html = await ejs.renderFile(view, data, /* >> */ {async: true} /* << */ );
res.send(html);

and in your .ejs file:

<%- await helper.getBrokerName(account.broker_id) ->
ganjim
  • 1,234
  • 1
  • 16
  • 30