F
F
fury20062022-02-02 11:12:17
AJAX
fury2006, 2022-02-02 11:12:17

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

2 answer(s)
N
Nadim Zakirov, 2022-02-02
@fury2006

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;
      
    }
    
  }

}

D
Dima Polos, 2022-02-02
@dimovich85

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 question

Ask a Question

731 491 924 answers to any question