Created
April 30, 2019 15:51
-
-
Save bladecoding/7a4d7061dbf1f0027b2770651f2efa41 to your computer and use it in GitHub Desktop.
JS async exports
This file contains 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
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