从节点中的回调函数返回值

Returning value from callback function in node

本文关键字:函数 返回值 回调 节点      更新时间:2023-09-26

我的node-js应用程序中有这个函数。我给它用户的位置在纬度和经度,一个半径,和一个关键字来搜索。有一个名为GooglePlace的节点模块,我一直在使用它将这些值传递给GooglePlace API。

function placesRequest(radius, lat, lon, keyword){  
    var conductor = new googlePlaces(googlePlacesAPIKey, "json");
    var parameters = {
        radius: radius,
        location:[lat, lon],
        types:"restaurant",
        query:keyword
    };
    conductor.placeSearch(parameters, function(error, response) {
        if (error) throw error;
        console.log(response.results) //for debugging
        if(response.status=="ZERO RESULTS") return "{results:0}";
        return response.results;
    });             
}

我对node.js还是比较陌生的,我一直在研究如何模块化函数,但我不完全确定它是如何工作的。我得到的最大收获是分别重写函数。有没有一种快速检索响应.results数据的方法,或者我应该只是卷曲请求?

您需要提供对placesRequest的回调才能获得结果:

function placesRequest(radius, lat, lon, keyword, callback){  
    var conductor = new googlePlaces(googlePlacesAPIKey, "json");
    var parameters = {
        radius: radius,
        location:[lat, lon],
        types:"restaurant",
        query:keyword
    };
    conductor.placeSearch(parameters, function(error, response) {
        /*
        Consider passing the error to the callback
        if (error) throw error;
        console.log(response.results) //for debugging
        if(response.status=="ZERO RESULTS") return "{results:0}";
        */
        callback(response.results);
    });             
}

所以你这样称呼地方请求:

placesRequest(1,2,3,'abc', function (results) {
  // do something with the results
});

是的,它很丑陋,当你依赖多次回报时,它可能会变得复杂。但在很多情况下,这已经足够了。

对于复杂的情况,您可以使用一些抽象,如:

  • 承诺
  • (或)类似async的实用程序库

我找到了解决方案,但为了保证解决方案,我应该更多地提及该项目。上面提到的功能是一个简单的地方搜索应该:

  1. 取用户输入的(纬度、经度、半径、关键字)

  2. 将这些值传递到谷歌位置

  3. 返回Google 返回的数据

然后,接收到的数据将作为对初始http请求的http响应发送,该请求将提供所需的所有数据。由于应用程序的性质,它需要处理不同的请求类型(地图搜索、用户配置文件编辑等),所以我实现了一个单独的功能,其中有一个开关案例

解决方案:

从函数中获取开关用例,并将其插入到运行http服务器的函数中。然后,使用placesRequest函数,将其放入switch案例中,然后从那里编写响应。这不是最漂亮的解决方案,但它有效。