2014-11-20 49 views
1

對於我的項目,我有一個server.js,它調用一個輔助函數place-search.js,如下所示。如何從輔助函數返回值到server.js NodeJS

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

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

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

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

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

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

 
module.exports.server = server;

這裏是我的地方,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,以便我可以使用該結果作爲另一個輔助函數的輸入。我不能爲我的生活弄清楚如何做到這一點。任何幫助都將不勝感激。

回答

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庫來管理一系列異步請求來收集一個組合結果。

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

好像你遇到與異步操作的麻煩。您需要return來自您的地方搜索模塊的承諾。您還需要將回調從placeSearch轉換爲承諾。

編輯:自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 
    }); 
}); 
+0

呀,儘管使用'VAR承諾=',它看起來沒有什麼實際上是一個承諾。 – Paul 2014-11-20 19:47:15

+0

我假設'googlePlaces.placeSearch'返回了一個承諾。 – 2014-11-20 20:35:11

+0

如果他使用的是npm模塊,請不要使用它.https://www.npmjs.org/package/googleplaces – Paul 2014-11-20 21:18:30