我正在try 为JavaScript类(我的应用程序中的控制器)编写一个"混合",在实际调用实际方法之前,自动"等待"给定的函数被解析.实类方法应接收解析值作为最后一个参数.
这是useAwait
的代码,我在这里寻找静态类属性awaits
,并将originalFunc
包装成一个新的async
.我调用新函数,将原始参数plus传递给asyncFn
调用结果:
const useAwait = (controller, asyncFn) => {
controller.constructor.awaits.forEach(func => {
const originalFunc = controller[func];
controller[func] = async (...args) => {
return originalFunc.apply(
controller,
[...args, await asyncFn.call(controller)]
);
};
});
}
因此,当在实例上调用useAwait(ctrl, this.load)
时,该类:
class Controller {
static awaits = ['foo', 'bar'];
promise;
constructor() {
useAwait(this, this.load);
}
async foo(e, resolved) {
return resolved;
}
bar(resolved) {
return resolved;
}
async load() {
if (!this.promise) {
this.promise = new Promise(resolve => setTimeout(() => {
resolve('Hello World!');
}, 3000));
}
return this.promise;
}
}
problem:对于foo
(已经是async
)来说一切似乎都很好,但对于bar
来说不是这样:结果是Promise
,因为现在bar
被包装在async
中(之前没有).我知道异步函数结果被包装到Promise
中.Codepen example其中bar
个调用输出"[对象promise ]".
所以question是:理论上,我应该判断原始函数是否为async
,如果不是,返回值为await
?