Want to access the value of a promise? This example I find self-explanatory. Notice how await waits for the result and so you miss the Promise being returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function await_getipv4(timeout = 1000) { var t1 = new Date(); while(!window.ipv4) { var stop = new Date() - t1 >= timeout; if(stop) { console.error('timeout exceeded for await_getipv4.'); return false; } } return window.ipv4; } function async_getipv4() { var ipv4 = null; var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}}) findIP.then(ip => window.ipv4 = ip); return await_getipv4(); }; |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.