我有一个API,该API返回带有有关服务器连接(更确切地说是ice服务器)信息的JSON对象:
{"v":{"iceServers":{"username":"XXXXXXXxxxXXXXXXxxxXXXXXXXxxxXXXXXXxxxXXXXXXXxxxXXXXXXxxxXXXXXXXxxxXXXXXXyyyy","urls":["stun:xxx.com","turn:xxxxyyyyyyyxx1","turn:xxxxyyyyyyyxx2","turn:xxxxyyyyyyyxx3","turn:xxxxyyyyyyyxx4","turn:xxxxyyyyyyyxx5","turn:xxxxyyyyyyyxx6"],"credential":"22222-11111-22222-33333"}},"s":"ok"}
我正在尝试将结果分配给javascript变量,但是我遇到了一些麻烦。这是我的代码:
// IceServersHandler.js
var IceServersHandler = (function() {
function getIceServers(connection) {
if (false) {
// NEW VERSION GETTING FROM API
var getIce = null;
getIce = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
var response = JSON.parse(xhr.responseText);
var theiceServers = [response.v.iceServers];
console.log(theiceServers); //DISPLAY CORRECTLY
callback(theiceServers);
}
}
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
}
function myCallback(data) {
return data;
}
var iceServers = getIce("/getservers",myCallback);
console.log(iceServers); // NOT DISPLAYING
} else {
// HOW I EXPECT THE DATA
var iceServers = [{
urls: [ "stun:xxx.com" ]
}, {
username: "XXXXXXXxxxXXXXXXxxxXXXXXXXxxxXXXXXXxxxXXXXXXXxxxXXXXXXxxxXXXXXXXxxxXXXXXXxxx",
credential: "12345123-12345123-12345123-12345123",
urls: [
"turn:xxxxyyyyzzzzz1",
"turn:xxxxyyyyzzzzz2",
"turn:xxxxyyyyzzzzz3",
"turn:xxxxyyyyzzzzz4",
"turn:xxxxyyyyzzzzz5",
"turn:xxxxyyyyzzzzz6",
]
}];
}
return iceServers;
}
return {
getIceServers: getIceServers
};
})();
在这段代码中,我保留了试图从API获取的版本以及预期的硬编码数组。在我运行函数IceServersHandler.getIceServers()
的那一刻,它显示为undefined,并在1秒钟后显示了该数组,但仅在函数作用域(// DISPLAY)中存在一个。
我在做什么错?另外,如何将结果分配给变量并显示为与“ HOW I EXPECT THE DATA”版本完全一样?
编辑1:我以this问题作为参考来建立我的示例,但仍然缺少一些内容。