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.