什么'这是让函数返回等待异步操作完成的最佳方法

What's the best way to get a function return to wait until an asynchronous operation has finished?

本文关键字:异步操作 等待 方法 最佳 返回 函数 什么      更新时间:2023-09-26

给定以下原型函数:

Client.prototype.getLocalIp = function() {
    var rtc = new window.RTCPeerConnection({iceServers: []});
    rtc.createDataChannel('', {reliable: false});
    var that = 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) {
        // Does lots of string processing stuff and returns a string
    }
    console.log("Returning from function");
    console.log(this.localIp);
}

grep函数完成其业务并返回值之前,如何阻止函数返回?以下是一个JSFiddle演示我的意思:http://jsfiddle.net/tjkxcL1j/

如果您查看浏览器控制台,您应该会看到getLocalIp()函数首先返回null,直到rtc.onicecandidate和/或rtc.createOffer的异步内容完成。

函数需要接受回调参数

Client.prototype.getLocalIp = function getLocalIp(done) {
  // ...
  rtc.createOffer(function (offer) {
    that.localIp = grep(offer.sdp);
    rtc.setLocalDescription(offer);
    // call the callback here
    done(null, that.localIp);
  },
  function (error) {
    console.warn('Fetching local IP failed', error);
    // call the callback with an error here
    done(error);
  });
};

然后你可以像这个一样使用它

client.getLocalIp(function(err, ip){
  if (err) return console.error(err.message);
  console.log("client ip", ip);
});

然而,正如@zerkms在评论中提到的那样,只有在实际发生异步操作的情况下,这才有效。示例包括通过网络访问信息或访问磁盘。