I have developed a controller that performs a Bing search based on the user's input in the URL. After testing the controller with console.log, it seems to be functioning correctly and I have set the variable to return the results. However, when trying to display the information on the page from the route file, nothing is showing up. I suspected it might be an asynchronous issue, so I am attempting to use promises to ensure that the controller has returned before calling res.json. Since I am not very familiar with promises, there may be a syntax error or I could be approaching this problem incorrectly. Can someone review the syntax and see if there is an issue? Currently, only an empty object is being displayed on the page.
app.route('/imagesearch/:keyword')
.get(function (req, res) {
var resObj = [];
resObj = new Promise (function(resolve, reject){
resolve(bingSearchHandler.findImages(req.params));
});
resObj.then(res.json(resObj));
});
//BINGSEARCHHANDLER
'use strict';
var bingAPPID = 'fwHyQAoJMJYmK8L4a3dIV2GAEUfXAlFRjCnBx0YbfPE=';
var Search = require('bing.search');
var util = require('util');
var search = new Search(bingAPPID);
function bingSearchHandler () {
this.findImages = function(userInput){
var keyword = userInput.keyword;
search.images(keyword,
{top: 10},
function(err, results) {
if(err)
{
console.log(err);
}
else
{
var resArr = [];
(util.inspect(results,
{colors: true, depth: null}));
for(var i=0;i<results.length;i++)
{
var tempObj = {};
tempObj.url = results[i].url;
tempObj.snippet = results[i].title;
tempObj.thumbnail = results[i].thumbnail.url;
tempObj.context = results[i].sourceUrl;
resArr.push(tempObj);
}
console.log(resArr);
return resArr;
}
}
);
}
}
module.exports = bingSearchHandler;