【发布时间】:2018-07-02 10:22:40
【问题描述】:
代码说明
我有一个从 html 输入中提取值并返回格式化地址的函数。我调用此函数两次,将每个地址存储到适当的变量中。一旦我转换了两个输入,我想调用另一个函数,function z。
ngAfterViewInit() {
//get input elements, get the first tag within the ion-input tag
this.searches.startSearch = document.getElementById("startSearch").getElementsByTagName('input')[0];
this.searches.endSearch = document.getElementById("endSearch").getElementsByTagName('input')[0];
var address1 = this.placeDecode(this.searches.startSearch)
var address2 = this.placeDecode(this.searches.endSearch)
this.methodZ(address1,address2);
}
//method convertes input into formatted address
private placeDecode(input : HTMLInputElement) {
var location = input.value;
var geoCode = new google.maps.Geocoder();
geoCode.geocode({
address: location
}, function (result, status) {
if (status === 'OK') {
return result[0].formatted_address;
} else {
return null;
}
});
}
问题
我遇到的问题是我只想在两个输入都转换后调用函数 Z。我曾尝试使用回调,但我无法在回调中调用 function z。
【问题讨论】:
-
这个函数没有任何作用。你
returning 什么都没有。为什么不能在回调中调用函数z?阅读并理解stackoverflow.com/q/14220321/476,那么您可能想使用Promise.all()来等待两个promise。 -
我没有显示我所有的代码,因为没有必要,你可以想象我调用placeDecode并检索结果,当在回调中调用z时,它说它是未定义的
-
我无法想象你如何调用
placeDecode并检索结果,因为placeDecode不会返回任何结果。 -
返回结果[0].formatted_address
-
是的,没有。这是从异步回调返回的,而不是从
placeDecode返回的。你真的真的需要阅读和理解这个:stackoverflow.com/a/14220323/476
标签: javascript asynchronous callback