0

I am using commercetool sdk where i have a file product.js which is fetching data from a graphql query

exports.getProduct = async function () {
    try {
       await apiRoot.withProjectKey({projectKey}).graphql()
            .post({
                body : {
                    query: projectSettingsQuery,
                    variables: {}
                }
            })
            .execute()
            .then(data => {
                if(data.statusCode == 200){
                    console.log(data.body.data.product.masterData.current.name);
                    return data.body.data.product.masterData.current.name;
                }
                console.log('Project information --->', data);
            })
            .catch(error => {
                console.log('ERROR --->', error);
            })
    } catch (error) {
        console.log('ERROR --->', error);
    }
}

It is returning the promise when called from app.js file, but consoling the right response

app.js file -

router.get('/product/:key', (req,res) => {
    const accountId = req.params.key;
    const acc = product.getProduct()
    res.send(`Hello World, This is home router key ${product.getProduct()} == ${acc}`);
});

The returned value here is [object Promise] I am not very experienced in this, can you please help me

atul1039
  • 143
  • 4
  • 13

1 Answers1

0

I would highly suggest reading up on how promises work as they are a cornerstone of node.js. However for your example you can simply await the response of your function call. i.e.

router.get('/product/:key', async (req,res) => {
    const accountId = req.params.key;
    const acc = await product.getProduct()
    res.send(`Hello World, This is home router key ${product.getProduct()} == ${acc}`);
});
Wodlo
  • 847
  • 5
  • 8