1

I have an express router set up in my back end that I want to return some information to my front end with, but I am trying to separate it out into separate functions so that I can re-use some of the functions.

When I make the request within my router function it behaves as expected, however when I break it out it always comes back as undefined, which makes me think I am not returning it correctly.

The following works, and returns the project link I am trying to get:

router.get('/test', (req, res) => {

    var options = {
        method: 'GET',
        url: url + '/api/projects',
        headers:
        {
            Cookie: req.params.token
        },
        qs: 
        {
            limit: '1000',
            q: `name:${req.params.project_name}` 
        }
    };

    request(options, (error, response, body) => {
        if (error) {
             throw new Error(error);
        }

        const jsonBody = JSON.parse(body);

        const projectLink = jsonBody.items[0]['_meta']['href']

        console.log(projectLink)

        return res.send({ "project_link": projectLink })
    });
})

However when I try to break the above request out into its own function and call it from router.get('/test') it comes back as undefined, however it logs the expected value within test():

router.get('/test', (req, res) => {
    let projectId;
    projectId = test(req.query.bearer_token, req.query.project_name);

    console.log('projID', projectId);
    return res.send(projectId)
})

let test = ( token, project_name ) => {

    var options = {
        method: 'GET',
        url: url + '/api/projects',
        headers:
        {
            Cookie: token
        },
        qs: 
        {
            limit: '1000',
            q: `name:${project_name}` 
        }
    };

    request(options, (error, response, body) => {
        if (error) {
             throw new Error(error);
        }

        const jsonBody = JSON.parse(body);

        const projectLink = jsonBody.items[0]['_meta']['href']

        console.log(projectLink)

        return projectLink
    });

}

I suspect there is a bit of request inception happening that is complicating things, as a request is being made from the front end which is calling a function that is returning a request. What is the proper way to return projectLink?

buffcat
  • 265
  • 2
  • 5
  • 17

1 Answers1

0

Its an asynchronous call, so you should use promise or async await, so that it proceeds only when the value is returned. Otherwise it will start executing next lines, and not wait.

const rp = require("request-promise");
router.get('/test', async (req, res) => {
    let projectId;
    projectId = await test(req.query.bearer_token, req.query.project_name);

    console.log('projID', projectId);
    return res.send(projectId)
})

let test = async (token, project_name) => {

    var options = {
        method: 'GET',
        uri: url + '/api/projects',
        headers: {
            Cookie: token
        },
        qs: {
            limit: '1000',
            q: `name:${project_name}`
        },
        json: true
    };

    const body = await rp(options)
    if (!body) {
        throw "api response ..........."
    }

    const jsonBody = JSON.parse(body);

    const projectLink = jsonBody.items[0]['_meta']['href']

    console.log(projectLink)

    return projectLink
}
Nayan Patel
  • 1,683
  • 25
  • 27