[英]How can i wait for my call without using async on my ngOnInit method?
I have the following code.我有以下代码。 To wait for my async call I am using the following
要等待我的异步调用,我正在使用以下
testi() {
return new Promise((resolve,reject) => {
resolve(true);
})
}
async ngOnInit() {
let pp = await this.testi();
console.log('pp', pp);
}
is there any other way with which I can wait for the call here without adding async
notation on my ngOnInit
method?有没有其他方法可以在这里等待调用而不在我的
ngOnInit
方法上添加async
表示法?
You can use then
instead of await
:您可以使用
then
而不是await
:
testi() {
return new Promise((resolve,reject) => {
resolve(true);
});
}
ngOnInit() {
this.testi()
.then(value => console.log(`pp: ${value}`))
}
If you are writing Typescript code, chances are that your compiled code will uses then
instead of await
.如果您正在编写 Typescript 代码,那么您的编译代码可能会使用
then
而不是await
。 It is the "old" way of using promises.这是使用 Promise 的“旧”方式。
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Promise/then https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
You can have a separated method that handles all the async parts and its result, and within your ngOnInit() you just call that method.您可以有一个单独的方法来处理所有异步部分及其结果,并在您的 ngOnInit() 中调用该方法。
async testi() {
let pp = await new Promise((resolve,reject) => {
resolve(true);
})
console.log('pp', pp)
}
ngOnInit() {
this.testi();
}
You can subscribe to it..你可以订阅它。。
ngOnInit() {
this.testi().subscribe((pp:any) => {
console.log('pp', pp);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.