Wednesday 18 November 2015

Can you make `require` itself an ES7 Async function?

I'm using ES7 Async/await Babel and it seems I have to do everything in an async function if I have to use awaitmain.jsvar fnA = require('./a.js'); async function main(){ var val = await fnA(); // do something with val } a.jsmodule.exports = async function fnA(){ return await somePromise(); } Wouldn't it be much better to have something like this:main.jsvar val = await require('./a.js') // do something with val a.jsmodule.exports = await somePromise(); I tried to write a require patch so that it can encapsulate the contents of the new file in an async function.__require = require; require = function require_async_patch() { var args = arguments; async function async_require_patch() { return __require(...args); } var prom = async_require_patch(); // prom: Promise { // _bitField: 33554432, // _fulfillmentHandler0: undefined, // _rejectionHandler0: 1, // <- this seems to be module.exports // _promise0: undefined, // _receiver0: undefined } return prom._rejectionHandler0 // todo: await prom } I haven't completely thought it through but even before I tried to go forward with this, it turns out Babel doesn't like await unless its inside an async function. It doesn't care if the parent require is patched to be an async function, it needs the asyn function in current visible context.Any workarounds? or am I chasing the wrong things?

Submitted November 19, 2015 at 07:21AM by laggingreflex

No comments:

Post a Comment