node.js - NodeJS -- cost of promise chains in recurssion -
i trying implement couple of state handler funcitons in javascript code, in order perform 2 different distinct actions in each state. similar state design pattern of java (https://sourcemaking.com/design_patterns/state).
conceptually, program need remain connected elasticsearch instance (or other server matter), , parse , post incoming data el. if there no connection available elasticsearch, program keep tring connect el endlessly retry period.
in nutshell,
- when not connected, keep trying connect
- when connected, start posting data
the main run loop calling recurssively,
function run(ctx) { logger.info("run: running..."); // starts disconnected state... return ctx.curstate.run(ctx) .then(function(result) { if (result) ctx.curstate = connectedst; // else remains in old state. return run(ctx); }); }
this not recursive fn in sense each invocation calling in tight loop. suspect ends many promises in chain, , in long run consume more n more memory , hence hang.
- is assumption / understanding right? or ok write kinda code?
- if not, should consider calling setimmediate / process.nexttick etc?
- or should consider using tco (tail cost optimization), ofcourse yet understand concept.
yes, returning new promise (the result of recursive call run()
), chain in promise.
neither setimmediate()
nor process.nexttick()
going solve directly.
when call run()
again, don't return
, should fine.
Comments
Post a Comment