Не могу понять, как вытащить данные из коллбэк-функции, подскажите, пожалуйста.
console.log(xhr(adress)); // undefined
function xhr(adress) {
const request = (resp) => {
// console.log(resp); // {"response":{"GeoObjectCollection": ...
let obj = JSON.parse(resp); // конвертируем из json в объект js //
obj = obj.response; // {GeoObjectCollection: {…}}
obj = obj.GeoObjectCollection; // {metaDataProperty: {…}, featureMember: Array(1)}
obj = obj.featureMember[0]; // GeoObject: {metaDataProperty: {…}, boundedBy: {…}, Point: {…}}
obj = obj.GeoObject.Point; // {pos: "37.620555 55.741333"}
const coords = obj.pos; // 37.620555 55.741333
return coords;
}
function httpGet(fullUrl) {
const xhr = new XMLHttpRequest();
xhr.open("GET", fullUrl, true);
xhr.send();
xhr.onreadystatechange = function() { // (3)
if (xhr.readyState === 4 && xhr.status === 200) {
const coords = request(xhr.responseText); // 37.620555 55.741333
return (coords);
}
}
}
const url = 'https://geocode-maps.yandex.ru/1.x/?';
const apikey = 'xxx&format=json&geocode=';
const fullUrl = url + apikey + adress;
return httpGet(fullUrl);
}