How to access the value of a promise?

后端 未结 12 2303
予麋鹿
予麋鹿 2020-11-22 06:55

I\'m looking at this example from Angular\'s docs for $q but I think this probably applies to promises in general. The example below is copied verbatim from the

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 07:17

    You can easily do that using an async wait method in javascript.

    Below is an example retrieving a WebRTC promise value using a timeout.

    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();
    };

提交回复
热议问题