Answer the question
In order to leave comments, you need to log in
js exit from for if inside ajax function call async with callback?
Help me figure out how to break the loop and still return the result of the function inside the loop.
But there is a nuance: in the loop, a function call in which, in turn, an asynchronous ajax request and the callback
itself. Here it is impossible to interrupt the loop when the result is not empty.
function sample(arr) {
var results;
searching:
for (let i = 0; i < arr.length; i++) {
results = searchingIdByName(arr[i], code, function(results) {
if (results !== undefined && results.id !== undefined) {
return results;
}
});
//тут всегда results undefined
if (results !== undefined && results.id !== undefined) {
console.log(results);
break searching;
}
}
}
function searchingIdByName(param, code, callback) {
$.ajax({
url: "...",
dataType: 'jsonp',
type: "GET",
delay: 250,
data: {q: param },
success: function(data) {
let results = data;
return callback(results);
}
});
}
Answer the question
In order to leave comments, you need to log in
Use async / await:
async function sample(arr) {
for (var i = 0; i < arr.length; i++) {
try {
var result = await $.ajax({
url: '...',
dataType: 'jsonp',
type: 'GET',
delay: 250,
data: { q: arr[i] }
});
if (result) {
console.log('Получен ответ:');
console.dir(result);
}
else {
console.log('Получен пустой ответ:');
console.dir(result);
console.log('Прерываем цикл...');
break;
}
}
catch (err) {
console.log('Ошибка:');
console.error(err);
console.log('Прерываем цикл...');
break;
}
}
}
We need to translate this into promises, and then, perhaps, use for await of (as one of the options), but immediately we need to think about browser support, although in theory everyone should already be able to.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question