function - Accessing variable outside of scope (javascript) -
i trying access variable outside of scope of function. trying access price outside of function. have wait until request finishes, or not have access price?
var httprequest = new xmlhttprequest(); httprequest.open('get', "https://api.iextrading.com/1.0/stock/aapl/quote", true); httprequest.send(); httprequest.addeventlistener("readystatechange", processrequest, false); function processrequest(e) { if (httprequest.readystate == 4 && httprequest.status == 200) { response = json.parse(httprequest.responsetext); console.log(response.latestprice); var lastprice = response.latestprice; document.getelementbyid("stockprice").innerhtml = lastprice; price = lastprice; } } document.write("outside: " + price);
you don't have access price
variable outside of function's scope. can instead return price, assign call function variable. example:
var price = processrequest();
however, call asynchronous, you'll either have make document.write
call within function, or you'll have setup kind of promise or callback ensure document.write
called once request complete (and price
assigned value).
that might like:
function writetodoc (price) { document.write("outside: " + price); } function processrequest(e, cb) { // request logic if (httprequest.readystate == 4 && httprequest.status == 200) { response = json.parse(httprequest.responsetext); console.log(response.latestprice); var lastprice = response.latestprice; document.getelementbyid("stockprice").innerhtml = lastprice; price = lastprice; // call callback function cb(price); } } httprequest.addeventlistener("readystatechange", processrequest.bind(this, writetodoc), false);
Comments
Post a Comment