admin管理员组文章数量:1025517
Sorry in advance for the long quest. I am trying to be as clear as possible with the issue that I am facing.
I have created a decorators utils library and I encountered a strange behaviour while working on one of the decorators (.ts).
The decorator is named "after" and it should execute a different function after the execution of the decorated method. But here is the thing, if the function is returning a promise the decorator should wait for it to be resolved and only then call the after func.
Here is relevant code:
if (resolvedConfig.wait) {
const response = await originalMethod.apply(this, args);
afterFunc({
args,
response
});
} else {
const response = originalMethod.apply(this, args);
afterFunc({
args,
response
});
}
As you can see I am one providing a flag for the decorator to indicate that the decorated method is an async function and it returns a Promise. I would be happy to get read of this flag by having the following code:
const response = await originalMethod.apply(this, args);
afterFunc({
args,
response
});
Basically, I want to always put await
before the execution of the original method, as from my understanding in case of sync method the await doesn't do anything.
The problem is with that when I am changing the code as suggested above, the following unit test fails:
it('should verify after method invocation when method is provided', () => {
let counter = 0;
const afterFunc = jest.fn(() => {
expect(counter).toBe(1);
});
class T {
@after<T, void>({
func: afterFunc
})
foo(x: number): void {
return this.goo(x);
}
goo(x: number): void {
expect(counter++).toBe(0);
return;
}
}
const t = new T();
const spyGoo = jest.spyOn(T.prototype, 'goo');
t.foo(1);
expect(spyGoo).toBeCalledTimes(1);
expect(spyGoo).toBeCalledWith(1);
expect(afterFunc.mock.calls.length).toBe(1); // this line fails
});
I have created a fork of the lib where this exact test is failing ().
What is wrong with my perception?
Sorry in advance for the long quest. I am trying to be as clear as possible with the issue that I am facing.
I have created a decorators utils library and I encountered a strange behaviour while working on one of the decorators (https://github./vlio20/utils-decorators/blob/master/src/after/after.ts).
The decorator is named "after" and it should execute a different function after the execution of the decorated method. But here is the thing, if the function is returning a promise the decorator should wait for it to be resolved and only then call the after func.
Here is relevant code:
if (resolvedConfig.wait) {
const response = await originalMethod.apply(this, args);
afterFunc({
args,
response
});
} else {
const response = originalMethod.apply(this, args);
afterFunc({
args,
response
});
}
As you can see I am one providing a flag for the decorator to indicate that the decorated method is an async function and it returns a Promise. I would be happy to get read of this flag by having the following code:
const response = await originalMethod.apply(this, args);
afterFunc({
args,
response
});
Basically, I want to always put await
before the execution of the original method, as from my understanding in case of sync method the await doesn't do anything.
The problem is with that when I am changing the code as suggested above, the following unit test fails:
it('should verify after method invocation when method is provided', () => {
let counter = 0;
const afterFunc = jest.fn(() => {
expect(counter).toBe(1);
});
class T {
@after<T, void>({
func: afterFunc
})
foo(x: number): void {
return this.goo(x);
}
goo(x: number): void {
expect(counter++).toBe(0);
return;
}
}
const t = new T();
const spyGoo = jest.spyOn(T.prototype, 'goo');
t.foo(1);
expect(spyGoo).toBeCalledTimes(1);
expect(spyGoo).toBeCalledWith(1);
expect(afterFunc.mock.calls.length).toBe(1); // this line fails
});
I have created a fork of the lib where this exact test is failing (https://github./vlio20/utils-decorators/pull/new/after-issue).
What is wrong with my perception?
Share Improve this question edited Feb 25, 2020 at 20:17 vlio20 asked Feb 25, 2020 at 20:07 vlio20vlio20 9,32518 gold badges101 silver badges186 bronze badges2 Answers
Reset to default 5 +50Basically, I want to always put await before the execution of the original method, as from my understanding in case of sync method the await doesn't do anything.
This is not true. According to the AsyncFunction reference on MDN (which itself directly references the ECMAScript spec), any function denoted as async
will always have the function body execute out of the regular call sequence.
In other words, the callee does not matter to the async/await function, it will always resolve asynchronously. This is important as a function should ideally only ever be synchronous or asynchronous and never both. This is enshrined in the return type of async functions: they will always yield a promise, regardless of what goes on inside of them, and promises can never be inspected synchronously.
The only way for you to acplish this is to avoid using await
/async
altogether and inspect the return type of your function directly:
const after = ({ func }) => (f) => (..args) => {
const value = f(...args)
if ('then' in value === false) {
func()
return value
}
return value.then(value => {
func()
return value
})
}
As you can probably tell from the tone of this answer (and my references), I do not think that it is a good approach to do this. Keeping your functions wholly synchronous or asynchronous would be advisable.
I hope this little code can help you:
a = async () => console.log(await 'a')
a()
console.log('b')
It will show b and only then a. Because if have await
then async function will always execute a bit later and you need to wait for it. That's why all of your sync functions in the test worked fine and the last one async one did not.
If you will add await
to t.foo(1)
test should pass.
My opinion is that it's better to do separate implementations of afterFunc
, luckily asyncness could be determined from function.name
Here is example closer to decorator problem:
let didDecoratorFinish = false
const decorator = (fn) => {
return async (...args) => {
await fn()
didDecoratorFinish = true
}
}
const test = () => {
let fnWasCalled = false
const fn = decorator(() => fnWasCalled = true)
fn()
console.log(fnWasCalled) // true
console.log(didDecoratorFinish) // guess what =)
}
test()
Again, solution is or to use await
in the test, or to make sync and async decorator implementation. For example (sorry, don't know typescript):
const afterFn = function(fn, afterFn) {
// you can use is-async-function npm package for example
if (isFunctionAsync(fn))
return (...args) =>
new Promise(async (resolve, reject) => {
try {
const result = await fn.apply(this, args)
await afterFn() // I don't know if you want to wait for afterFn
resolve(result)
} catch (err) {
reject(err)
}
})
else
return (...args) => {
const result = fn.apply(this, args)
afterFn() // it can be async, I don't know if you want to wait for it
return result
}
}
Sorry in advance for the long quest. I am trying to be as clear as possible with the issue that I am facing.
I have created a decorators utils library and I encountered a strange behaviour while working on one of the decorators (.ts).
The decorator is named "after" and it should execute a different function after the execution of the decorated method. But here is the thing, if the function is returning a promise the decorator should wait for it to be resolved and only then call the after func.
Here is relevant code:
if (resolvedConfig.wait) {
const response = await originalMethod.apply(this, args);
afterFunc({
args,
response
});
} else {
const response = originalMethod.apply(this, args);
afterFunc({
args,
response
});
}
As you can see I am one providing a flag for the decorator to indicate that the decorated method is an async function and it returns a Promise. I would be happy to get read of this flag by having the following code:
const response = await originalMethod.apply(this, args);
afterFunc({
args,
response
});
Basically, I want to always put await
before the execution of the original method, as from my understanding in case of sync method the await doesn't do anything.
The problem is with that when I am changing the code as suggested above, the following unit test fails:
it('should verify after method invocation when method is provided', () => {
let counter = 0;
const afterFunc = jest.fn(() => {
expect(counter).toBe(1);
});
class T {
@after<T, void>({
func: afterFunc
})
foo(x: number): void {
return this.goo(x);
}
goo(x: number): void {
expect(counter++).toBe(0);
return;
}
}
const t = new T();
const spyGoo = jest.spyOn(T.prototype, 'goo');
t.foo(1);
expect(spyGoo).toBeCalledTimes(1);
expect(spyGoo).toBeCalledWith(1);
expect(afterFunc.mock.calls.length).toBe(1); // this line fails
});
I have created a fork of the lib where this exact test is failing ().
What is wrong with my perception?
Sorry in advance for the long quest. I am trying to be as clear as possible with the issue that I am facing.
I have created a decorators utils library and I encountered a strange behaviour while working on one of the decorators (https://github./vlio20/utils-decorators/blob/master/src/after/after.ts).
The decorator is named "after" and it should execute a different function after the execution of the decorated method. But here is the thing, if the function is returning a promise the decorator should wait for it to be resolved and only then call the after func.
Here is relevant code:
if (resolvedConfig.wait) {
const response = await originalMethod.apply(this, args);
afterFunc({
args,
response
});
} else {
const response = originalMethod.apply(this, args);
afterFunc({
args,
response
});
}
As you can see I am one providing a flag for the decorator to indicate that the decorated method is an async function and it returns a Promise. I would be happy to get read of this flag by having the following code:
const response = await originalMethod.apply(this, args);
afterFunc({
args,
response
});
Basically, I want to always put await
before the execution of the original method, as from my understanding in case of sync method the await doesn't do anything.
The problem is with that when I am changing the code as suggested above, the following unit test fails:
it('should verify after method invocation when method is provided', () => {
let counter = 0;
const afterFunc = jest.fn(() => {
expect(counter).toBe(1);
});
class T {
@after<T, void>({
func: afterFunc
})
foo(x: number): void {
return this.goo(x);
}
goo(x: number): void {
expect(counter++).toBe(0);
return;
}
}
const t = new T();
const spyGoo = jest.spyOn(T.prototype, 'goo');
t.foo(1);
expect(spyGoo).toBeCalledTimes(1);
expect(spyGoo).toBeCalledWith(1);
expect(afterFunc.mock.calls.length).toBe(1); // this line fails
});
I have created a fork of the lib where this exact test is failing (https://github./vlio20/utils-decorators/pull/new/after-issue).
What is wrong with my perception?
Share Improve this question edited Feb 25, 2020 at 20:17 vlio20 asked Feb 25, 2020 at 20:07 vlio20vlio20 9,32518 gold badges101 silver badges186 bronze badges2 Answers
Reset to default 5 +50Basically, I want to always put await before the execution of the original method, as from my understanding in case of sync method the await doesn't do anything.
This is not true. According to the AsyncFunction reference on MDN (which itself directly references the ECMAScript spec), any function denoted as async
will always have the function body execute out of the regular call sequence.
In other words, the callee does not matter to the async/await function, it will always resolve asynchronously. This is important as a function should ideally only ever be synchronous or asynchronous and never both. This is enshrined in the return type of async functions: they will always yield a promise, regardless of what goes on inside of them, and promises can never be inspected synchronously.
The only way for you to acplish this is to avoid using await
/async
altogether and inspect the return type of your function directly:
const after = ({ func }) => (f) => (..args) => {
const value = f(...args)
if ('then' in value === false) {
func()
return value
}
return value.then(value => {
func()
return value
})
}
As you can probably tell from the tone of this answer (and my references), I do not think that it is a good approach to do this. Keeping your functions wholly synchronous or asynchronous would be advisable.
I hope this little code can help you:
a = async () => console.log(await 'a')
a()
console.log('b')
It will show b and only then a. Because if have await
then async function will always execute a bit later and you need to wait for it. That's why all of your sync functions in the test worked fine and the last one async one did not.
If you will add await
to t.foo(1)
test should pass.
My opinion is that it's better to do separate implementations of afterFunc
, luckily asyncness could be determined from function.name
Here is example closer to decorator problem:
let didDecoratorFinish = false
const decorator = (fn) => {
return async (...args) => {
await fn()
didDecoratorFinish = true
}
}
const test = () => {
let fnWasCalled = false
const fn = decorator(() => fnWasCalled = true)
fn()
console.log(fnWasCalled) // true
console.log(didDecoratorFinish) // guess what =)
}
test()
Again, solution is or to use await
in the test, or to make sync and async decorator implementation. For example (sorry, don't know typescript):
const afterFn = function(fn, afterFn) {
// you can use is-async-function npm package for example
if (isFunctionAsync(fn))
return (...args) =>
new Promise(async (resolve, reject) => {
try {
const result = await fn.apply(this, args)
await afterFn() // I don't know if you want to wait for afterFn
resolve(result)
} catch (err) {
reject(err)
}
})
else
return (...args) => {
const result = fn.apply(this, args)
afterFn() // it can be async, I don't know if you want to wait for it
return result
}
}
本文标签: javascriptAsync call in a TypeScript decoratorStack Overflow
版权声明:本文标题:javascript - Async call in a TypeScript decorator - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745632563a2160249.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论