Defer expression
kai zhu
kaizhu256 at gmail.com
Fri Aug 18 14:26:08 UTC 2017
i can give you a specific solution to one of my async init problems
(done entirely in vanilla es5 code). in this use-case, i want to run
integrated tests, but have to wait for the server to listen on a port,
and the db to be seeded first. to keep complexity at a manageable
level, i find its worth the tradeoff to pollute the global namespace
with initialization functions and counters, especially if you intend
to break up the below example into separate modules.
```js
global.initializationCounter = 0;
global.initializationCounterDecrement = function () {
/*
* this function will decrement the initialization counter,
* and if the initialization counter reaches zero, then run the post-init code
*/
global.initializationCounter -= 1;
if (global.initializationCounter === 0) {
global.postInit();
}
};
global.postInit = function () {
/*
* run your custom post-init code here
*/
// run test-runner after initialization
global.testRun();
};
...
var db, http, server;
http = require('http');
// pre-init1 - create http server,
// and wait for server to listen to port 8080, before running post-init code
server = http.createServer(function (request, response) {
// request handler
...
});
global.initializationCounter += 1;
server.listen(8080, global.initializationCounterDecrement);
// pre-init2 - create db,
// and wait for db to seed, before running post-init code
db = ...;
global.initializationCounter += 1;
db.insert(<data1>, global.initializationCounterDecrement);
global.initializationCounter += 1;
db.insert(<data2>, global.initializationCounterDecrement);
// pre-init3 - any extra async init code
global.initializationCounter += 1;
setTimeout(function () {
// you custom code
...
global.initializationCounter();
});
```
On 8/18/17, Matthew Robb <matthewwrobb at gmail.com> wrote:
> Yeah essentially although I'd think of it more as sugar for:
>
> (async () => { await null; ... })()
>
> On Aug 17, 2017 4:17 PM, "Tab Atkins Jr." <jackalmage at gmail.com> wrote:
>
>> On Thu, Aug 17, 2017 at 12:12 PM, Matthew Robb <matthewwrobb at gmail.com>
>> wrote:
>> > Honestly have there been any proposals for something like `do async {
>> > //
>> can
>> > await here }` which would produce a promise in the enclosing scope
>>
>> Do-expressions haven't advanced in general yet, but if/when they do,
>> this seems like it might be reasonable. It's just sugar for the
>> `Promise.resolve().then(()=>{...})` expression, right?
>>
>> ~TJ
>>
>
More information about the es-discuss
mailing list