Skip to content

Instantly share code, notes, and snippets.

@bladecoding
Created April 30, 2019 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bladecoding/7a4d7061dbf1f0027b2770651f2efa41 to your computer and use it in GitHub Desktop.
Save bladecoding/7a4d7061dbf1f0027b2770651f2efa41 to your computer and use it in GitHub Desktop.
JS async exports
let Delay = (ms) => new Promise(res => setTimeout(res, ms));
exportsAsync = new Proxy(()=>{}, {
get(t, k) {
const resource = k;
return new Proxy({}, {
get(t, k) {
return (...args) => {
return new Promise((resolve, reject) => {
let cb = (err, data) => { if (err) reject(err); else resolve(data); };
exports[resource][k].apply(void 0, [cb, ...args]);
});
};
},
set() {
throw new Error('cannot set values on an export resource');
}
});
},
apply(t, self, args) {
if (args.length !== 2) {
throw new Error('this needs 2 arguments');
}
const [ exportName, func ] = args;
exports(exportName, (cb, ...args) => {
if (typeof cb !== 'function')
throw Error("async export called without callback first");
let promise = func.apply(void 0, args);
if (!(promise instanceof Promise))
promise = Promise.resolve(promise);
promise.then(r => cb(null, r)).catch(err => cb(err, null));
});
},
set() {
throw new Error('cannot set values on exports');
}
});
exportsAsync("add", async (x,y) => {
await Delay(500);
return x+y;
});
setImmediate(async () => {
console.log(await exportsAsync[GetCurrentResourceName()].add(1,2));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment