Я пишу функции в своем файле JavaScript для вывода адреса. Это не самый чистый вариант, но он работал до того, как возникла моя текущая проблема. Я пытаюсь использовать callback и получить адрес, но когда я записываю адрес в console, это undefined. Я не уверен, что делаю не так.
function calculateDistance(vnames, vlocations) {
// PROGRAM NEVER GOES THROUGH THIS???
clientLoc((address) => {
var origin = address;
alert("Address: " + address);
});
// PROGRAM NEVER GOES THROUGH THIS???
console.info("my location is: " + origin);
var venueNames = vnames,
venueLocs = vlocations,
service = new google.maps.DistanceMatrixService();
// 5. Output band name and distance
// Matrix settings
service.getDistanceMatrix(
{
origins: [origin],
destinations: venueLocs,
travelMode: google.maps.TravelMode.DRIVING, // Calculating driving distance
unitSystem: google.maps.UnitSystem.IMPERIAL, // Calculate distance in mi, not km
avoidHighways: false,
avoidTolls: false
},
callback
);
// Place the values into the appropriate id tags
function callback(response, status) {
// console.info(response.rows[0].elements)
// dist2 = document.getElementById("distance-result-2"),
// dist3 = document.getElementById("distance-result-3");
for(var i = 1; i < response.rows[0].elements.length + 1; i++) {
var name = document.getElementById("venue-result-" + i.toString()),
dist = document.getElementById("distance-result-" + i.toString());
// In the case of a success, assign new values to each id
if (status= = "OK") {
// dist1.value = response.rows[0].elements[0].distance.text;
name.innerHTML = venueNames[i-1];
dist.innerHTML = response.rows[0].elements[i-1].distance.text;
} else {
alert("Error: " + status);
}
}
}
}
Это функция, которую я использую в callback:
// Find the location of the client
function clientLoc (callback) {
// Initialize variables
var lat, lng, location
// Check for Geolocation support
if (navigator.geolocation) {
console.info('Geolocation is supported!');
// Use geolocation to find the current location of the client
navigator.geolocation.getCurrentPosition(function(position) {
console.info(position);
lat = position.coords.latitude;
lng = position.coords.longitude;
// Client location coordinates (latitude and then longitude)
location = position.coords.latitude + ', ' + position.coords.longitude
// console.info(location)
// Use Axios to find the address of the coordinates
axios.get('https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAg3DjzKVlvSvdrpm1_SU0c4c4R017OIOg', {
params: {
address: location,
key: 'AIzaSyBH6yQDUxoNA3eV81mTYREQkxPIWeZ83_w'
}
})
.then(function(response) {
// Log full response
console.info(response);
var address = response.data.results[0].formatted_address;
// Return the address
console.info(address);
//return clientLoc.address;
// CALLBACK
callback(address);
})
});
}
else {
console.info('Geolocation is not supported for this Browser/OS version yet.');
return null;
}
}



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


функция, имеющая обратный вызов, не блокирует выполнение, поэтому вызывается ваша функция clientLoc и, предположительно, если этот код работает, переменная origin будет установлена, и ваш вызов предупреждения будет срабатывать ... НО код ниже clientLoc не ждет вызов clientLoc для завершения ... он выполняет остальную часть функции ... при условии, что я не слишком знаком с синтаксисом es6, но концепция та же. Вероятно, вы захотите переместить console.info («мое местоположение:» + origin); и любой код, который полагается на исходную переменную, установленную внутри обратного вызова, чтобы сделать его более чистым, используйте некоторые обещания
Спасибо! Изначально меня беспокоило, что остальная часть кода не дожидалась готовности запроса местоположения. Я переместил код за пределы обратного вызова clientLoc внутри него. Как бы вы сделали его чище с помощью обещаний?