javascript - What's the best way to get a function return to wait until an asynchronous operation has finished? -
given next prototype function:
client.prototype.getlocalip = function() { var rtc = new window.rtcpeerconnection({iceservers: []}); rtc.createdatachannel('', {reliable: false}); var = this; rtc.onicecandidate = function(event) { if (event.candidate) { that.localip = grep(event.candidate.candidate); } }; rtc.createoffer(function (offer) { that.localip = grep(offer.sdp); rtc.setlocaldescription(offer); }, function (error) { console.warn('fetching local ip failed', error); }); var grep = function(sdporcandidate) { // lots of string processing stuff , returns string } console.log("returning function"); console.log(this.localip); }
how can stop function returning until grep
function has finished doing business , returned value? here's jsfiddle demonstrating mean: http://jsfiddle.net/tjkxcl1j/
if in browser console should see getlocalip()
function returning null first until async stuff rtc.onicecandidate
and/or rtc.createoffer
finished.
your function needs take callback argument
client.prototype.getlocalip = function getlocalip(done) { // ... rtc.createoffer(function (offer) { that.localip = grep(offer.sdp); rtc.setlocaldescription(offer); // phone call callback here done(null, that.localip); }, function (error) { console.warn('fetching local ip failed', error); // phone call callback error here done(error); }); };
then can utilize this
client.getlocalip(function(err, ip){ if (err) homecoming console.error(err.message); console.log("client ip", ip); });
however, @zerkms mentions in comment, going work if async operations happening. examples include accessing info on network or accessing disk.
javascript asynchronous
No comments:
Post a Comment