0

I have an Axios get request hitting a search API. When I console.log the response in the then() function, I can see the objects just fine. However, when I try to capture them in a variable so that I can pass them into my rendered view, my variable comes back as Promise { pending }. How can I capture the JSON response? Thanks.

let axios = require('axios');

let bing_web_search = function(search) {
    let searchEncoded = encodeURIComponent(search);
    return axios.get(
        'https://api.cognitive.microsoft.com/bing/v7.0/search?q=' + searchEncoded + '+site:https://learn.microsoft.com/en-us/azure/&mkt=en-us', {
            headers: { 'Ocp-Apim-Subscription-Key' : process.env.BING_SUBSCRIPTION_KEY }
        })
    .then(function(response) {
        return response.data.webPages;
    })
    .catch(function(error) {
        console.log(error)
    });
}

module.exports = {
    bing_web_search : bing_web_search
}

I am then calling this function in my controller as follows:

router.get('/search/results', function(req, res) {
    let searchResults = bing.bing_web_search(req.query.search_query);
    let test = searchResults.then(function(results) {
        return results;
        //console.log(results); <--This shows objects just fine in the console
    });
    console.log(test); //<--This returns Promise { pending }
    res.render('../views/results', {
        test : test
    });
})

How can I capture this JSON object so that I can iterate through it in my view file?

edit: That explanation is referencing using the actual Promise function. I'm using Axios which seems to automatically turn my get request into a promise so I'm trying to understand how to do it within the scope of Axios. I'm not using AJAX/jQuery as most of those examples give. Would appreciate any responses that help me understand.

A. Cam
  • 139
  • 2
  • 10
  • ` so that I can iterate through it in my view file?` move the rendering stuff *into* the `then` handler?! – Jonas Wilms Apr 10 '18 at 18:51
  • The problem with that is that I am going to be using multiple results to be passed in to that route. So moving the route into the function wouldn't really work because it needs access to multiple variables, each of which return different API results. – A. Cam Apr 10 '18 at 20:43
  • Then include those! We cant give accurate answers to incomplete questions. But whatsoever, you can use `Promise.all` to put multiple promises results into one chain. – Jonas Wilms Apr 11 '18 at 11:52

0 Answers0