Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Dennis Eitner
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dennis Eitner
Full Stack JavaScript Techdegree Graduate 25,644 Points

How do I create a middleware in node function that makes the response-object available in another module/function

exports.middleware = (req, res, next) => {
    const requestOptions = {
        //some request options from api
      };

      rp(requestOptions)
        .then(response => {
            let globalObject = response.data;
// I want this object available in other functions
            for (let index = 0; index < globalObject.length; index++) {
                console.log( globalObject[index]);
            }
        })
        .catch(err => {
          console.log("API call error:", err.message);
        });
    next();
};
Kevin Gates
Kevin Gates
15,053 Points

Made easier to see by adding js after the initial backticks

exports.middleware = (req, res, next) => {
    const requestOptions = {
        //some request options from api
      };

      rp(requestOptions)
        .then(response => {
            let globalObject = response.data;
// I want this object available in other functions
            for (let index = 0; index < globalObject.length; index++) {
                console.log( globalObject[index]);
            }
        })
        .catch(err => {
          console.log("API call error:", err.message);
        });
    next();
};
Steven Parker
Steven Parker
231,269 Points

Have you noticed that you get different colors if you use "js" vs "javascript"?

using "js":

            for (let index = 0; index < globalObject.length; index++) {

using "javascript":

            for (let index = 0; index < globalObject.length; index++) {

I never know which to use anymore!

1 Answer

Kevin Gates
Kevin Gates
15,053 Points

I think the issue is that the let keyword is limiting that variable only inside of the promise. So you need to return the globalObject for it to be available outside its current scope. Read more about promises here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises