Implementing promises in my MEAN stack application

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;

Answer №1

Are you looking for a solution? I recommend giving this code a try. You can find the documentation for bing.search here. It's always a good practice to use callbacks instead of promises in NodeJs. Remember that the first parameter of a callback is usually the error, followed by the response.

app.route('/imagesearch/:keyword')
.get(function (req, res) {
    bingSearchHandler.findImages(req.params, function (err, response) {
      if (err) return res.status(400)

      res.json(response)
    })
});

//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, callback){
    var keyword = userInput.keyword;
    search.images(keyword,
          {top: 10},
          function(err, results) {
            if(err) callback(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 callback(null, resArr);
                }
          }
        );
  }

}

module.exports = bingSearchHandler;

Answer №2

Here is an example of how to implement this.

Utilizing callbacks

app.route('/imagesearch/:keyword')
    .get(function (req, res) {
        // Perform async request and pass the callback function
        bingSearchHandler.findImages(req.params, (error, response) => {
            if (error === null) {
                res.json(response);
            }
        });
    });

You will also need to revise your findImages function.

this.findImages = (userInput, callback) => {
    var keyword = userInput.keyword;
    search.images(keyword, {top: 10}, function (err, results) {
        if (err) {
            callback(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);
            }
            callback(null, resArr);
        }
   });
}

Using promises

app.route('/imagesearch/:keyword')
    .get(function (req, res) {
        // Perform async request and use a promise
        bingSearchHandler.findImages(req.params).then(response => 
            res.json(response);
        });
    });


// Images function
this.findImages = (userInput) => {
    return new Promise((resolve, reject) => {
        var keyword = userInput.keyword;
        search.images(keyword, {top: 10}, function (err, results) {
            if (err && typeof reject === 'function') {
                reject(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);
                }
                if (typeof resolve === 'function') {
                    resolve(resArr);
                }
            }
        });
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I convert an Array into a Dictionary using JavaScript?

Is there a clever method (perhaps using a map function) to restructure my data object from this: [ {id: 1, from: "1/1/2021", to: "1/2/2022"}, {id: 2, from: "1/3/2021", to: "1/4/2022"}, {id: 1, from: "1/5/2 ...

Using the get method instead of delete in an express application

As I was diving into the process of removing a collection from MongoDB using express, I came across the concept of app.delete for deletion. However, upon closer inspection of my code, it seems like the actual deletion is carried out by Todos or MongoDB thr ...

Adjusting the transparency of the object's interior

I used the side property to give my object an interior, but it also reflects the exterior: let material = new THREE.MeshStandardMaterial({side: THREE.DoubleSide}); https://i.sstatic.net/oikad.png https://i.sstatic.net/Vb03K.png Is there a way to red ...

Transmitting text data within Google Analytics

I'm currently working on binding events for tracking with Google Analytics. When calling GA, we also have the option to send a value along with it. My goal is to send a value using a DOM selector. For example, when I use: myValue=function(){return ...

Adjusting the sound levels of an HTML audio element using JavaScript

I'm looking to adjust the volume of an <audio> element when a user clicks on an image. HTML: <div id="cloud"> <img name="jsVolumeButton" src="images/cloud.png" width = "140px"/> </div> <audio id="player" src="sounds/rain. ...

Retrieving selections from a group of checkboxes and managing their addition or removal in an array

Currently, I am in the process of creating a form that includes a group of checkboxes. My goal is to be able to capture the value of a specific checkbox when it is clicked and add it to an Array using the useState hook. If the checkbox is unchecked, I wan ...

What is the best way to implement jQuery after new elements have been added to the DOM?

I'm currently working on a Sentence Generator project. The program is designed to take a list of words and retrieve sentences from sentence.yourdictionary.com based on those words. The first sentence fetched from the website is displayed using the cod ...

Deleting a button from a list item or array in Angular 12

Having some trouble removing a list item with the click button, I've tried a few options but nothing seems to be working. Can anyone offer assistance? I need to remove a list item from my users array when clicked. Below is the Typescript code and cor ...

The method firebaseApp.auth does not exist in user authentication using Firebase

Implementing user authentication with Firebase in my React webapp has been a challenge due to issues with the firebaseAuth.app() function. Despite trying various solutions such as reinstalling firebase dependencies, updating imports to SDK 9 syntax, and ad ...

$scope variables, ng-hide/show directive

There seems to be a confusion with $scope in my code. I have ng-hide/shows that use a variable in the top nav, controlled by "NavController". Inside an ng-view, controllers are linked via the app config function. The appointment setting functionality is ha ...

What could be the reason why I am unable to choose my radio button? What error am I

The output can be found here... I am struggling to use a radio button and cannot seem to select it. Can someone please explain what issue I am facing? Any help would be greatly appreciated. const [value, setValue] = React.useState({ yes:"", no:"" ...

Choosing the parent folder that is at least two levels above in JavaScript

My directory structure is: /project Login |1.1 js |1.2 db Main Within the 'db' folder, there is a script that utilizes AJAX to determine if a user is an admin or regular user. The goal is to redirect to a page stored in the 'Main&apo ...

Is it a Mozilla Firefox glitch or something else?

After writing the code, I noticed a bug in Firefox and a small bug in Chrome. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> ...

What is the best approach to transfer information from the client side to a node

I have an ejs page that looks like this: <%- include('../blocks/header', {bot, user, path}) %> <div class="row" style="min-width: 400px;"> <div class="col" style="min-width: 400px;"> <div class="card text-white mb-3" & ...

Transform text that represents a numerical value in any base into an actual number

Looking to convert a base36 string back to a double value. The original double is 0.3128540377812142. When converting it to base 36: (0.3128540377812142).toString(36); The results are : Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi Firefox: 0.b9ginb6s73e Now, h ...

Why is the React onClick method returning undefined upon the first selection, and why are the values being passed not consistent with

While attempting to create a list of users that, when clicked, should open up a corresponding user's message, I encountered an issue where clicking for the first time resulted in an 'undefined' value being passed. I've tried troublesho ...

"Integrating Laravel 5.4 Backend with Angular 5 Frontend: A Step-by-Step

Currently, I am immersed in a project that involves creating a frontend using Angular 5 and backend business logic using Laravel 5.4 with MySQL Database. As someone new to this technology stack, I find myself grappling with establishing the data flow conne ...

What is the best way to manage data that arrives late from a service?

Within my Angular application, I have a requirement to store data in an array that is initially empty. For example: someFunction() { let array = []; console.log("step 1"); this.service.getRest(url).subscribe(result => { result.data.forEach( ...

Encountered an error with ng build --prod while attempting to import a JavaScript file within the app module

Is it possible to import a javascript file into my app module without access to the ts file? import { OtherComponent } from './node_modules/blahblah/OtherComponent.js' While trying to declare this component in @NgModule and running "ng build -- ...

Firebase Error: Trying to access properties of null object (indexOf)

Whenever I try to console.log(docSnap), a Firebase error shows up as seen in the image below. Despite attempting various solutions, none have proved effective. https://i.sstatic.net/9R4vE.png useEffect(() => { if (folderId === null) { ...