Skip to content

Instantly share code, notes, and snippets.

@stelf
Last active August 8, 2023 01:54
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save stelf/d97ab0156461ffc5fbc65be54b936abf to your computer and use it in GitHub Desktop.
Save stelf/d97ab0156461ffc5fbc65be54b936abf to your computer and use it in GitHub Desktop.
using ES6 proxies and async/await to dynamically, yet almost transparently connect to some remote data provider
let providerHandler = {
get: async(target, name) => {
console.log('load someting from remote...')
return new Promise( (res, rej) => {
setTimeout(() => res(42), 4200)
})
},
set: function (obj, prop, value) {
return new Promise((res, rej) => {
console.log('save someting remotely...')
setTimeout(() => res(true), 1000)
})
}
}
let recieverHandler = {
get: async (target, name) => {
if (target.prop instanceof Promise) {
return target.prop.then(res => target[name] = res)
} else {
return target[name]
}
},
set: function (obj, prop, value) {
obj[prop] = value
}
}
async function main() {
let dynrecv = new Proxy({}, recieverHandler)
let dynprov = new Proxy({}, providerHandler)
dynrecv.prop = await dynprov.prop // await it here
console.log(await dynrecv.prop)
dynrecv.another = dynprov.another // direct assign here, no await
console.log(await dynrecv.another)
await dynprov.setme("value") // store someting remotely.
// it's up to u to decide await or not
}
main()
@ethansnow2012
Copy link

ethansnow2012 commented Mar 9, 2021

Thanks for sharing. Just what I am looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment