问题描述
我知道ES6的 await
功能,我想在类中创建的函数中使用它.
I know of the ES6 await
feature and I’d like to use it in a function I created in a class.
它工作正常,但是当该函数是 static
函数时,则不能.有什么理由吗?另外,在 static
函数中使用 await
的正确方法是什么?
It works well, but when the function is a static
function, it doesn’t. Is there any reason for that? Also, what will be the right way to be able to use await
inside a static
function?
class MyClass {
resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
static async asyncCall() {
console.log('calling');
var result = await this.resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
}
MyClass.asyncCall();
推荐答案
您可以在静态函数中正常使用 await
.那不是你的问题.
You can use await
just fine in a static function. That is not your issue.
但是,静态函数中的 this
是 MyClass
,因此 this.someMethod()
正在寻找另一种静态方法,而不是实例方法并且 resolveAfter2Seconds()
是一个实例方法,而不是静态方法,因此 this.resolveAfter2Seconds()
不会找到该方法,因为这就像调用 MyClass.resolveAfter2Seconds()
不存在.
BUT, this
in a static function is MyClass
so this.someMethod()
is looking for another static method, not an instance method and resolveAfter2Seconds()
is an instance method, not a static method so this.resolveAfter2Seconds()
won't find that method because that's like calling MyClass.resolveAfter2Seconds()
which doesn't exist.
如果您还使 resolveAfter2Seconds()
成为 static
,则可能会起作用,因为 asyncCall()中的
this
code>是 MyClass
,所以 this.resolveAfter2Seconds()
正在寻找另一种静态方法.
If you also make
resolveAfter2Seconds()
be static
, then it would probably work because this
inside asyncCall()
is MyClass
so this.resolveAfter2Seconds()
is looking for another static method.
这应该在将
resolveAfter2Seconds
设置为静态的情况下起作用:
This should work where you make
resolveAfter2Seconds
also be static:
class MyClass {
static resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
static async asyncCall() {
console.log('calling');
var result = await this.resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
}
或者,您可以进入原型并从那里调用它,因为它实际上是一个静态方法(根本不引用
this
):
Or, you could reach into the prototype and call it from there because it is actually a static method (doesn't reference
this
at all):
static async asyncCall() {
console.log('calling');
var result = await MyClass.prototype.resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
这篇关于“等待this.method();"不适用于静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!