【发布时间】:2020-01-27 16:46:26
【问题描述】:
我正在做一个 Ionic 4 项目。这对我来说在 Javascript / Typescript 中工作是相当新的,我很难理解如何正确使用 async / await / promise 和所有这些东西。
我有什么:
在我的应用程序的一个页面上(我们称之为 tab1.page.ts)我有一个调用我的服务函数的函数:
Get_Sim_Agents() {
this.simConfig.Get_Sim_Agents();
}
在我的服务页面,这里是函数:(一个基本的http get函数):
/**
* Fetch the datas in order to populate the app
* */
Get_Sim_Agents(){
this.http.get(
"http://" +
this.ip_address +
":" +
this.port +
"/get_datas"
).subscribe(response => {
var data = JSON.stringify(response, null, 2);
try {
var obj = JSON.parse(data);
// here i do stuff with the retrieved data
});
} catch (e) {
console.log(e);
}
});
}
一切正常。但是我希望我的服务函数在检索和处理数据时将数据作为字符串返回。我很难找到正确的语法。 这是我尝试过的:
为我服务:
/**
* Fetch the Sim_Agents from the Simulation_orchestrator in order to populate the app
* */
async Get_Sim_Agents() : Promise<string>{
this.http.get(
"http://" +
this.simulation_orchestrator_ip_address +
":" +
this.simulation_orchestrator_port +
"/get_sim_agents"
).subscribe(response => {
var data = JSON.stringify(response, null, 2);
// here i do some stuff about the data
return JSON.parse(data);
});
return 'test';
}
在我的页面上:
Get_Sim_Agents() {
this.simConfig.Get_Sim_Agents().then((result) => {console.log(result)});
}
使用此代码,我在页面上调用的函数立即返回“测试”。我希望它等到 http get 返回服务器响应。我尝试了几种不同的语法,但无法实现我想要的:confused:
要明确:
我正在寻找的是一种方法:
1/ 页面调用服务函数 2/服务提出请求,并得到回复 3/ 服务做事(用每个示例的数据填充应用程序) 4/ 然后它向页面发送一个字符串,比如“工作完成”
但我能找到的只是将服务的响应直接发送到页面的解决方案,而不需要服务的任何预处理
【问题讨论】:
-
试试
await this.http.get();您没有告诉async函数等到它有数据。 -
不,问题是他在函数末尾返回了一个字符串,而不是一个 Promise。
-
this.http是什么,.get()返回什么?找到一个返回承诺的 http 库。
标签: javascript typescript promise