如何将 api 响应分配给变量
How to assign api response to variable
我正在使用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;
};
相关文章:
- 在运行时使用预先确定的对象分配变量
- 重新分配变量和重新定义之间的性能差异
- Javascript:在对象中分配变量时命名函数的好处
- Angularjs 控制器在服务方法返回之前从服务中分配变量
- 在 JavaScript 中的 for 循环中重新分配变量的目的是什么?
- 按设置的数量拆分字符串,并为拆分分配变量
- 嵌套的 if/else 语句讨论了分配变量.我已经这样做了,但它仍然不起作用
- 有没有理由不在 while 块声明中分配变量
- JSON - 访问 JSON 数组并分配变量
- Angular2 火力基地检索并分配变量
- 是否可以在运行依赖项之前在 gulp 任务中分配变量
- 在 JS 中的 for 循环中重新分配变量是什么意思
- 使用多种组合分配变量的最佳方法是什么
- 使用函数从字符串中分配变量名称
- 如何调用chrome.storage.sync.get并在页面加载时分配变量
- 在JavaScript中用冒号分配变量的语法有效吗
- 带有单选按钮的If语句不分配变量
- 正在从内部回调中分配变量
- Javascript在匿名函数中分配变量的值
- 使用jQuery分配变量类型时出错