如何将值从辅助函数返回到server.js NodeJS

时间:2014-11-20 19:18:02

标签: javascript node.js

对于我的项目,我有一个server.js调用辅助函数place-search.js,如下所示。

var express = require('express');
var server = express.Router();

var placeSearch = require("./helpers/place-search");
var obj = "hello";

server.use(function(req, res, next) {
	console.log(req.method, req.url);
	next();
}); 

server.post('/', function(req, res) {
	/* get the object passed by the client's post request */
	obj = req.body;

	//console.log("Obj: " + obj);

	/* send the confirmation back to the client */
	res.status(200).send("body");
	placeSearch.placeSearch(obj);
});

module.exports.server = server;

这是我的place-search.js:

var config = require("./config.js");
var Promise = require('bluebird');
var DistanceMatrix = require("./distance-matrix.js");
var GooglePlaces = Promise.promisifyAll(require("googleplaces"));
var googlePlaces = new GooglePlaces(config.apiKey, config.outputFormat);
var extract = require('./extract.js');
var combination = require('./combination_ver2.js');
var permutation = require('./permutation.js');

function placeSearch(obj) {

    console.log("Inside place search!");

    /**
     * Place search - https://developers.google.com/places/documentation/#PlaceSearchRequests
     */
    var arr = [];
    var count = 0;
    var rad = obj["radius"];
    
    console.log("radius: " + rad);
    var loc = obj["location"];
    console.log("Location: " + loc);
    var mode = obj["mode"];

    var params = obj["params"];

    /* client's keywords */
    var arr;
    var ar = [];
    for (var i = 0; i < params; i++) {
        arr[i] = obj[i];
        console.log(arr[i]);
        var param = {
            location: loc,
            radius: rad,
            mode: mode,
            keyword: arr[i]
        };
        ar.push(param);
    }

    console.log("before promises");

    var promises = ar.map(function(name) {
        return googlePlaces.placeSearch(name, function(response) {
            arr.push(response);
            console.log(response);
            console.log(count++);
            //If all responses have been returned
            //Find combos and pass to distance-matrix
            if (count == ar.length) {
                var Matrix = new Array();
                var result = new Array();

                //to extract only lat and lng from arr.results
                //Matrix = extract.extract(arr);
                result = combination.combination(arr);

                // NOW RESULT IS THE ARRAY OF ALL COMBINATION

                // NOW RESULT IS THE ARRAY OF COMBINATIONS OF latlng pairs AND PASS IT TO FRONTEND
                /*result.forEach(function(combo, index) {
                    console.log("combo" + combo)
                    DistanceMatrix.distanceMatrix(mode, combo, result.length);
                });*/


                // IF YOU WANT TO SEE PERMUTATION
                //permutation.permutation(result);

                console.log("combination results: " + result);

            }

        })
    });

}

module.exports.placeSearch = placeSearch;

我的问题是我不知道如何将结果变量传递回server.js,以便我可以将该结果用作另一个辅助函数的输入。我不能为我的生活弄清楚如何做到这一点。任何帮助都将非常感激。

3 个答案:

答案 0 :(得分:0)

好吧,我没有看到你的placeSearch函数现在返回任何东西,也没有做任何回调。你的placeSearch函数应该公开一个回调参数,然后在你想要发回的答案后调用它。

然后,您的服务器文件将对该回调执行操作。缩写你的代码,它看起来像这样:

server.post('/', function(req, res) {
    /* get the object passed by the client's post request */
    obj = req.body;

    //console.log("Obj: " + obj);
    placeSearch.placeSearch(obj, function(error, data){
       /* send the data back to the client */
       res.status(200).send(data);
    }); 
});

为了支持这一点,你的placeSearch函数必须在适当的时候调用它的回调:

function placeSearch(obj, callback){

   /* all the stuff you do to assemble your data */
   // if (there_is_some_error):
   if(err) return cb(err);

   // when you have all your data available, no error has occurred
   return cb(null, data);
}

您可能会注意到的另一件事是您的ar.map无法按照您的预期运作。 ar.map是一个同步函数,你在里面调用异步代码......不会像你想象的那样工作。这篇文章有点长,但您应该从npm查看async库来管理一组异步请求以收集一个组合结果。

答案 1 :(得分:0)

使用回调你的代码如下:

function placeSearch(obj,callback) {

    console.log("Inside place search!");

    /**
     * Place search - https://developers.google.com/places/documentation/#PlaceSearchRequests
     */
    var arr = [];
    var count = 0;
    var rad = obj["radius"];

    console.log("radius: " + rad);
    var loc = obj["location"];
    console.log("Location: " + loc);
    var mode = obj["mode"];

    var params = obj["params"];

    /* client's keywords */
    var arr;
    var ar = [];
    for (var i = 0; i < params; i++) {
        arr[i] = obj[i];
        console.log(arr[i]);
        var param = {
            location: loc,
            radius: rad,
            mode: mode,
            keyword: arr[i]
        };
        ar.push(param);
    }

    console.log("before promises");

    var promises = ar.map(function(name) {
        return googlePlaces.placeSearch(name, function(response) {
            arr.push(response);
            console.log(response);
            console.log(count++);
            //If all responses have been returned
            //Find combos and pass to distance-matrix
            if (count == ar.length) {
                var Matrix = new Array();
                var result = new Array();

                //to extract only lat and lng from arr.results
                //Matrix = extract.extract(arr);
                result = combination.combination(arr);

                // NOW RESULT IS THE ARRAY OF ALL COMBINATION

                // NOW RESULT IS THE ARRAY OF COMBINATIONS OF latlng pairs AND PASS IT TO FRONTEND
                /*result.forEach(function(combo, index) {
                    console.log("combo" + combo)
                    DistanceMatrix.distanceMatrix(mode, combo, result.length);
                });*/


                // IF YOU WANT TO SEE PERMUTATION
                //permutation.permutation(result);

                console.log("combination results: " + result);

                callback(null,result);
            }

        })
    });

}

在server.js中:

server.post('/', function(req, res) {
    /* get the object passed by the client's post request */
    obj = req.body;

    //console.log("Obj: " + obj);

    /* send the confirmation back to the client */
    res.status(200).send("body");
    placeSearch.placeSearch(obj,function(err,result){
       if(!err){
console.log(result);
}
})
});

答案 2 :(得分:0)

您似乎遇到了异步操作问题。您希望return来自您的地点搜索模块的承诺。您还需要将来自placeSearch的回调转换为promise。

编辑:更新,因为googlePlaces.placeSearch没有返回承诺

placeSearch

function placeSearch(obj) {
  //...
  var promises = ar.map(function(name) {
    var placeDefer = Q.defer();

    return googlePlaces.placeSearch(name, function(response) {
      placeDefer.resolve(response); // or placeDefer.reject if a failure occurs
    });
    return placeDefer.promise;
  });

  return promises;
}

并在您的路线中:

// I'm going to just assume Q promise library here
var Q = require("q");

server.post('/', function(req, res) {
    /* get the object passed by the client's post request */
    obj = req.body;

    //console.log("Obj: " + obj);

    /* send the confirmation back to the client */
    res.status(200).send("body");

    Q.all(placeSearch.placeSearch(obj))
    .spread(function() {
      var places = Array.prototype.slice.call(arguments);

      // possibly call res.status(200).send("body"); here?
      // only if you're trying to use the places in your response
    });
});