问题描述
我需要这样做并在调用下一个函数之前分配返回的存储值,该函数也具有异步函数。这是第一个函数调用:
getUnits(){
this.storage.get('units').then((val => {
if (val != null){
this.units = val;
console.log("Settings.TS: #28 Got units : " + this.units);
}else{
this.units = "metric";
console.log("Settings.TS: #31 No saved units found,assigning metric.")
}
}));
this.getUnits();
console.log("WEaTHER.TS Getting City Weather...city / country = " + city + " / " + country);
if (country != null || country != ""){
city = city+","+country;
console.log("WEATHER.TS: coutry code enterView,city = " + city + " and units: " + this.units);
}
//https://api.openweathermap.org/data/2.5/weather?q=dublin&appid=4f91a3e665c56d59e4c7d9045d38e85a
const weatherjson = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&units="+ this.units + "&appid="+this.appid;
console.log("WEATHER.TS Getting this API call : " + weatherjson);
return this.http.get(weatherjson);
当代码执行时,控制流在两个函数之间来回传递,因为它们是异步的。
我的问题是无论如何我可以保证函数 A 在紧随其后的 close 块执行之前完全执行吗?
解决方法
对于异步函数,如果您想确保仅在函数 A 执行完毕后才调用函数 B,您可以在函数 A 的 then
块中调用函数 B。例如,在您的情况下像这样
getUnits(){
this.storage.get('units').then((val => {
if (val != null){
this.units = val;
console.log("Settings.TS: #28 Got units : " + this.units);
}else{
this.units = "metric";
console.log("Settings.TS: #31 No saved units found,assigning metric.")
}
//Call the second function here
}));