A module for weak referenced callbacks with timeouts.
A node.js module for weak referenced callbacks with timeouts.
var candle = require'candle'candle;var c = id;id = cadd console.log'cb1' err result; 100;// this will fire at 50ms and output "cb1 null result1.1"setTimeoutcresolvebindc id null 'result1.1' 50;// will fire at 60ms but will not activate the callback since it will have been fred by this time.setTimeoutcresolvebindc id null 'result1.2' 60;id = cadd console.log'cb2' err result; 100;// this will fire at 150ms, but the callback will have been activated by timeout and output "cb2 timeout "setTimeoutcresolvebindc id null 'result2' 150;// This will fire by timeout and will output "cb3 timeout "id = cadd console.log'cb3' err result; 100;
Server2 is known that it has unpredictable response time:
socketon'myrequest'// dont send anything at all about 'r3'if payload == 'r3' return;// send response after 10ms for 'r1', but after 1000ms for 'r2'.var timeout = payload == 'r1' ? 10 : 1000;setTimeoutsocketemit'myresponse' id payload + '_response';timeout;;
Server1 want to send some requests to the Server2 and wait for at most 100ms.
var candle = require'candle'candle;var c = ;var start = Datenow;socketon'myresponse'cresolveid null response;;varconsole.log'got' err request 'on' Datenow - start 'th ms';;socketemit'myrequest' 'r1' cadddoSmthWithRequest 100;socketemit'myrequest' 'r2' cadddoSmthWithRequest 100;socketemit'myrequest' 'r3' cadddoSmthWithRequest 100;
This code will likely output the following:
got null r1_response on 13 th msgot timeout on 102 th msgot timeout on 102 th ms
Also candle destroys (unreferences) all callback after they have been resolved or timed out to free memory and avoid leaks. As far as the r2_response will be returned after timeout it will be completely ignored.