简体   繁体   中英

Using promises in my mean stack app

I've created a controller that does a bing search based on the user's input into the url. Based on my results from doing a console.log the controller is working correctly and I have set that variable to return. In the route file the information is not displaying to the page. I thought it might be an asynchronous issue so I am trying to use promises to make sure the controller has returned before it tries to do the res.json but I'm not very familiar with promises so my syntax might be off or I might be going about this the wrong way. Will someone take a look at this syntax and see if there is an issue.Currently only an empty object is displaying 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;

Something like this should work.

Using callbacks

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

Additionally, you'll need to rework 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) {
        // Make the async request, pass the callback function
        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);
                }
            }
        });
    });
}

Could you please try this code? Here you have the bing.search documentation, https://www.npmjs.com/package/bing.search Always try to use callbacks instead of promises in NodeJs, remember that the first parameter of a callback is always the error (if there is any), then 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM