从 Typescript 承诺返回字符串值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43498131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning a string value from a Typescript promise
提问by spankymac
OK, here should be some simple Typescript code. In my mind anyway...
好的,这里应该是一些简单的 Typescript 代码。反正在我心里...
public showDialog(theNickname: string): string {
var req = {
method: 'POST',
url: '/Q/GetUserDetails',
data: { nickname: theNickname }
}
this.$http(req).then((response) => {
var c = "Nickname: " + response.data.Nickname + "<br/>";
c = c + "Score: " + response.data.Score + "<br/>";
c = c + "Followers: " + response.data.Followers + "<br/>";
return c;
});
}
Of course, it is not returning the string value as it is being returned as a promise. I don't want to use a timeout function. How can I return the string value? It is being called from an Angular function on the html. If I change
当然,它不会返回字符串值,因为它是作为承诺返回的。我不想使用超时功能。如何返回字符串值?它是从 html 上的 Angular 函数调用的。如果我改变
public showDialog(theNickname: string): string {
to
到
public showDialog(theNickname: string): any {
it still doesn't work. I am using this code in a UI.Bootstrap Popover.
它仍然不起作用。我在 UI.Bootstrap Popover 中使用此代码。
Thanks!
谢谢!
回答by Daryl
Paleo answer is correct, but you could be even awesomer and use Async/Await:
Paleo 的答案是正确的,但您可以使用 Async/Await 甚至更棒:
async function showDialog(theNickname: string): Promise<string> {
const req = {
method: 'POST',
url: '/Q/GetUserDetails',
data: { nickname: theNickname }
}
const response = await this.$http(req);
return `Nickname: ${response.data.Nickname
}<br/>Score: ${response.data.Score
}<br/>Followers: ${response.data.Followers}<br/>`;
}
async function caller() {
const message = await showDialog("TEST");
alert(message);
}
Check it out here
检查出来这里