0

I am trying to skip a loop iteration based on the ajax response. The problem I'm facing is that I'm unable to use the response from Ajax outside the Ajax call. Currently I solved it by using the below solution but here the problem is that I'm using async: false which is not recommended as Ajax call is async.

function ajaxCallHere(name) {
    let url = '/admin/someUrl/' + name;
    var skipName = '';
    $.ajax({
        'url': url,
        'type': 'GET',
        async: false,
        'success': function (data) {
            skipName = data.skip;
        }
    });
    return skipName;
}

function getAllNames() {
    for (let i = 0; i < names.length; i++) {
        var skipVal = ajaxCallHere(names.fullName);

        if(skipVal == 'yes') {
            continue;
        }
    }
}
1
  • In your success function, have you tried: getAllNames(data.skip) and using that in your getAllNames function? Commented Jun 29, 2022 at 19:42

1 Answer 1

1

Use async/await, since $.ajax returns an object that obeys the Promise protocol.

function ajaxCallHere(name) {
  let url = '/admin/someUrl/' + name;
  return $.get(url);
}

async function getAllNames() {
  for (let i = 0; i < names.length; i++) {
    var data = await ajaxCallHere(names.fullName);
    if (data.skipVal == 'yes') {
      continue;
    }
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.