我对javascript中的Promise实现还是很陌生的。虽然我得到了一个简单的示例,但在我弹出Google API elevation回调函数后,它不起作用。如果有人能帮助我实现这个功能,我将非常感激,因为我打算在我的应用程序中多次使用这种方法。
这是我当前的Promise函数代码(在javascript类结构中定义):
LinkClass.prototype.getElev = function(coordinate)
{
return new Promise(function(resolve,reject)
{
//get User elevation again, because it is possible that the user elevation did not lock
var locations = []; //locations array
locations.push(coordinate);
// Create a LocationElevationRequest object using the array's one value
var positionalRequest = {'locations': locations}
//get User elevation for antenna elevation calculation
var elevator = new google.maps.ElevationService();
elevator.getElevationForLocations(positionalRequest, function(results, status)
{
if (status == google.maps.ElevationStatus.OK)
{
// Retrieve the first result
if (results[0])
{
resolve(results[0].elevation.toString());
}
else
reject('No valid result was determined from the Google Elevation service. Please try again');
}
else
reject('Google Elevation service was not available. Please try again');
});
}); //end of promise function
}然后我在哪里实现函数:
LinkClass.prototype.drawLine = function()
{
//do other stuff...
this.getElev(this.UserLocation).then(function(response){
//for now just print the result
alert(response);
},function(Errortxt){
alert(Errortxt);
});
//do other stuff
}我真的需要让它工作,请!谢谢
发布于 2015-07-16 15:27:17
完全忘了张贴这个问题的答案。再次感谢您的投入。无论如何,我在这里发布的代码对于实现promises是正确的,如果你想同步和使用回调函数的答案,那么它真的很酷……对于所有的实际目的,这将在默认情况下在大多数浏览器中工作,不包括外部的"Promise javascript“文件或其他任何东西,除了Internet Explorer。(他们应该很快就会开始注意到,他们的浏览器开发技能正在消失)。
下面是我使用标准promise实现的链接,支持最低浏览器版本:) Promise browser impl & support
https://stackoverflow.com/questions/28275038
复制相似问题