that's general question using setimmediate (or similar solutions) api purpose. i'm writing node.js library performs negotiation server behind scene. client code of library seems that:
var request = mylib .createrequest() .setrequestproperty('someproperty', somevalue) .setanotherrequestproperty('anotherproperty', anothervalue) .performrequest(function callback() { var somevalue = request.somevalue; var requestresult = request.result; // logic based on requestresult , somevalue }); the problem begins when library not need perform or wait negotiation server, may call callback passed performrequest immediately. internal library code may seems like:
request.prototype.performrequest = function performrequest(callback) { if (this._canperformimmediately()) { callback(); return this; } this._performserverrequest().then(callback); return this; }; what happens request still undefined (as call callback done before external statement contains request assignment finished).
i wonder correct way define api in such cases. see possibilities:
- define callback may called synchronously (as described above), , client code may not use
requestvariable in above client code example. i've seen code seems above, guess not solution. define callback may called synchronously, , request passed callback client code may (notice use of
request_instead ofrequest):.performrequest(function callback(request_) { var somevalue = request_.somevalue; var someresult = request_.result; // logic based on requestresult , somevalue }(edit: request may passed
thisargument).but again, i've seen code seems first example, guess not solution.
guarantee callback called asynchronously. can use setimmediate functions. internal implementation (notice
setimmediatecall):request.prototype.performrequest = function performrequest(callback) { if (this._canperformimmediately()) { setimmediate(callback); return this; } this._performserverrequest().then(callback); return this; };any other suggestions?
it seems setimmediate alternative attractive, failed find discussion using api consideration only. i've seen discussions performance such here , here, no api considerations.
so question is: correct way implement such library?
Comments
Post a Comment