Refer the Mozilla document about Proxy()
A simple Proxy example:
const handler = {
get: function(target, prop, receiver) {
return Reflect.get(target, prop, receiver);
},
set: function(target, prop, receiver) {
return Reflect.set(target, prop, receiver);
}
};
const proxy = new Proxy(target, handler);
I have some async functions in get
and set
, so I would like to let get
and set
to be async
functions.
I expect something like:
const handler = {
get: async function(target, prop, receiver) {
await foo();
return Reflect.get(target, prop, receiver);
},
set: async function(target, prop, receiver) {
await bar();
return Reflect.set(target, prop, receiver);
}
};
const proxy = new Proxy(target, handler);
await (proxy.prop1 = xxx);
yyy = await proxy.prop2;
How can I achieve my goal? Thanks!
This is not possible. An assignment expression proxy.property = value
always1 evaluates to value
, not some return value of the proxy's set
trap. You cannot make it return an await
able promise.
1: unless the assignment, including the proxy traps, throws an exception of course.