Search code examples
node.jsejses6-promise

Get Promise Data and store it to a variable to be sent for EJS template


Final task: Display api search results on a EJS template.

Process: Using request and promise, I have the data on a promise of my search api call data.

Problem: How do I pass the string data of the “Promise” into my EJS template?

  • Promise only lets me access it via ‘search-api-results-received.then(result_i_need=>console.log(result_i_need)’. I can see it printed but I need it on a variable to pass it on to template.

I tried doing (result_i_need => temp_var_defined_outside = result_i_need) No luck!

Really struggling and pulling my hair. 😓😓😓Any help appreciated. Thanks

var params = {
  method: "POST",
  uri: `http://api.somewebsite.com/content/search/v1?apiKey=${
    process.env.API_KEY
  }`,
  body: JSON.stringify({
    queryString: req.query.find,
  }),
};

const rp = require("request-promise");
call_search_api = rp(params)
  .then(a => (call_search_api = a))
  .catch(er => console.log("err" + er));
// const call_search_api = searchlib(params,postData).then(a=>console.log(a));
var result = call_search_api.resolve(call_search_api);


res.render('search', {apidata: call_search_api});

Inside EJS template

<% var total_pages = apidata.results.length; %>


Solution

  • So since you're using Express, good news is this isn't hard. Express doesn't really care where you call res.render(), so long as you do call it... So put it in the API .then() function:

    const rp = require("request-promise");
    
    app.get("/something", (req, res) => {
      const params = {
        method: "POST",
        uri: `http://api.somewebsite.com/content/search/v1?apiKey=${
          process.env.API_KEY
        }`,
        body: JSON.stringify({
          queryString: req.query.find,
        }),
      };
    
      rp(params)
        .then(apidata => {
          res.render("search", { apidata });
          res.end();
        })
        .catch(er => {
          console.log("err" + er);
          res.end(); // TODO: better error handling
        });
    });
    

    Better yet, if you can use async functions:

    const rp = require("request-promise");
    
    app.get("/something", async (req, res) => {
      const params = {/* ... as above ... */};
    
      const apidata = await rp(params);
      res.render("search", { apidata });
      // TODO: missing error handling
    });