-
-
Save miguelrk/f616153f4395905c2f831b6df522fcc7 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const 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) | |
}) | |
} | |
} | |
const 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 receiver = new Proxy({}, recieverHandler) | |
let provider = new Proxy({}, providerHandler) | |
receiver.prop = await provider.prop // await it here | |
console.log(await receiver.prop) | |
receiver.another = provider.another // direct assign here, no await | |
console.log(await receiver.another) | |
await provider.set("value") // store someting remotely. up to you to decide await or not | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment