JS очерёдность выполнения кода
Суть проблемы в примере ниже. При изменении input запускается test(), выполняющий расчёт расстояния от одного адреса до другого, расчёт занимает время, в итоге нарушается очередность работы, должна быть: 1,2,3, а в примере 1,3,2. Как это проще всего победить.
$('input[name=addr]').change(function() {
console.log('1. значение input изменилось');
test(function() {
console.log('2. test() считает расстояние');
});
console.log('3. получен ответ от test()');
});
function test(resolve) {
geocoder = new ymaps.geocode(refineAddress(getFullAddress())).then(function(res) {
router = new ymaps.route([
from_address(),
to_address()
]).then(function(route) {
//набор вычислений, его результат рассчитанный километраж от адрес from_address() до адреса to_address()
console.log('удалённость: ' + km);
}, function(error) {
console.log(error.message);
});
}, function(error) {
console.log(error.message);
});
resolve();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="addr" value="0">
Ответы (1 шт):
Автор решения: Igor
→ Ссылка
$('input[name=addr]').change(function() {
console.log('1. значение input изменилось');
test(function() { console.log('3. получен ответ от test()'); });
});
function test(resolve) {
setTimeout(function() {
console.log('2. получен ответ от сервера');
resolve();
}, 500);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="addr" value="0">
$('input[name=addr]').change(function() {
console.log('1. значение input изменилось');
test(function() {
console.log('2. ');
}, function() {
console.log('3. ');
});
});
function test(r1, r2) {
geocoder = new ymaps.geocode(refineAddress(getFullAddress())).then(function(res) {
r1();
router = new ymaps.route([
from_address(),
to_address()
]).then(function(route) {
r2();
//набор вычислений, его результат рассчитанный километраж от адрес from_address() до адреса to_address()
console.log('удалённость: ' + km);
}, function(error) {
console.log(error.message);
});
}, function(error) {
console.log(error.message);
});
resolve();
}