在我的平均堆栈应用程序中使用promises

时间:2016-04-26 21:30:56

标签: javascript express asynchronous

我已经创建了一个控制器,可以根据用户对网址的输入进行搜索。基于我执行console.log的结果,控制器正常工作,我已将该变量设置为返回。在路径文件中,信息不显示到页面。我认为这可能是一个异步问题所以我试图使用promises来确保控制器在尝试执行res.json之前已经返回但我对promises不是很熟悉所以我的语法可能会关闭或者我可能是错误的方式。有人会看看这个语法,看看是否有问题。目前只有一个空对象显示在页面上。

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;

2 个答案:

答案 0 :(得分:0)

这样的事情应该有效。

使用回调

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);
            }
        });
    });

此外,您还需要重新设计findImages功能。

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);
        }
   });
}

使用承诺

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);
                }
            }
        });
    });
}

答案 1 :(得分:0)

你能试试这段代码吗?在这里你有bing.search文档,https://www.npmjs.com/package/bing.search总是尝试在NodeJs中使用回调而不是promises,记住回调的第一个参数总是错误(如果有的话),那么响应

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;