javascript - How to set a variable via asynched xmlhttprequest response -
what trying accomplish can done if create synched requests, since deprecated updating script work correctly asynch calls instead when other method stops working script continues working.
the current code using follows:
function get(a) { var request = new xmlhttprequest(), data; request.open("get", a, false); request.onreadystatechange = function () { if(4 == request.readystate) info = request.responsetext; }; request.send(); homecoming data; } function getobject(a) { var constructor = {}; constructor.property1 = 'something1'; constructor.property2 = 'something2'; constructor.property3 = 'something3'; constructor.property4 = true; if(a && a.attribute === null) constructor.property5 = get('/url-location'); homecoming constructor; } var object = getobject(a); if(object.property5) dosomethingwith(object);
as can see request conducted @ run-time in order set value constructor object. works because synchronus , function waits response before moving on, allowing value set before object returned.
however, same not happen when request runs asynch because function moves on without waiting response.
my problem evident; possible replicate same behaviour asynch requests? if not how accomplish same construction without modifying much? , mean creation of constructor object requires created in way presented; set multiple properties in sequence 1 time getobject called , homecoming when finished.
i cannot utilize libraries, no jquery, node, etc. avoiding timed/looped functions.
one more detail forgot: function used function different structure, similar objective, isn't simple changing function work illustration provided.
pass callback function get
, , phone call it:
function get(a, callback) { // <== alter here var request = new xmlhttprequest(); // <== no need `data` request.open("get", a, true); request.onreadystatechange = function () { if(4 == request.readystate) callback(request.responsetext); // <== alter here }; request.send(); }
usage (also callback, didn't phone call out changes, they're above):
function getobject(a, callback) { var constructor = {}; constructor.property1 = 'something1'; constructor.property2 = 'something2'; constructor.property3 = 'something3'; constructor.property4 = true; if(a && a.attribute === null) get('/url-location', function(data) { constructor.property5 = data; callback(constructor); }); }
usage:
getobject(a, dosomethingwith);
or if need object
variable:
var object; getobject(a, function(data) { object = data; dosomethingwith(object); });
...but note object
undefined
until callback happens (e.g., until xhr phone call completes).
another way promises, still involves callbacks, different (and arguably more powerful/convenient) style of chaining them.
javascript
No comments:
Post a Comment