如何将 api 响应分配给变量

How to assign api response to variable

本文关键字:分配 变量 响应 api      更新时间:2023-09-26

我正在使用DirectionsService类向谷歌服务器发送API请求,并获得响应。但是我无法将该响应分配给变量。

我尝试了以下方式它不起作用(未定义)。

var gettingApiresponce=function(sourcePlace,destinationPlace){
var directionService=new google.maps.DirectionsService();
var responce;
directionService.route(
    {
        origin:sourcePlace,
        destination:destinationPlace,
        travelMode:"DRIVING"
    },function(res,status){
        responce=res;
    });
return responce;
 };

我该如何解决这个问题。

方向服务是异步的。 任何使用响应的内容都应在回调函数中(或之后)运行。 因此,您无法"返回"结果。

// put in the global scope.
var responce;
var gettingApiresponce=function(sourcePlace,destinationPlace){
var directionService=new google.maps.DirectionsService();
directionService.route(
    {
        origin:sourcePlace,
        destination:destinationPlace,
        travelMode:"DRIVING"
    },function(res,status){
        //this will set the global variable responce, but anything that needs to be 
        // done with the returned value should be done here.
        responce=res;
        var directionsRenderer = new google.maps.DirectionsRenderer();
        directionsRenderer.setDirections(res);
        directionsRenderer.setMap(map);
        // etc.            
    });
    // can't do this returns before the callback function runs.
    //return responce;
 };