skip to Main Content

I’ve seen various answers to this question but I’m having trouble mapping them to my situation. What I think might be the answer on some of them, seem to be old ways of coding or unfamiliar enough to me that I cannot understand how to implement them to my situation.

I’ve got PHP generating a records.json file which my app needs to query for the logic of several methods.

function queryRecords(recordId, requiredField) {
    $.ajax("javascript/records.json", {
        dataType: "json",
        success: callBack,
        error: function (jqXhr, textStatus, errorMessage) {
            alert("AJAX error: unable to retrieve records from records.jsonnn" + errorMessage);
        }
    });
}

function callBack(response) {
    $.each(response, function(index, records) {
        if (records["MediaItemID"] == recordId) {
            $.each(records, function(key, value) {
                if (key == requiredField) {
                    return value;
                }
            });
        }
    });
}

queryRecords("14", "MediaItemName");

Each time I need to query the records, I need to pass recordId and requiredField to get the value of that record’s field (as per the loops in the callBack method). However it seems I am limited with this approach because I cannot pass these values as parameters in success. If I output to the console within success, I see the value, but I need access to the value outside of success and this is how far I’ve gotten. I’ve seen so many pages about this, my head hurts. Please can you help?

2

Answers


  1. Chosen as BEST ANSWER

    I tested the code suggested in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function just to see if I could access the value outside of the Promise, and it failed as it has always been doing...

    var xyz = "please";
    
    function resolveAfter2Seconds() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('resolved');
        }, 2000);
      });
    }
    
    async function asyncCall() {
      console.log('calling');
      const result = await resolveAfter2Seconds();
      xyz = result;
      //console.log(result);
      // expected output: "resolved"
    }
    
    asyncCall();
    
    console.log(xyz);
    

    It returns 'please'.

    Either I'm not understanding the solutions provided, or what I'm trying to achieve is not being understood. I'm happy to accept that this is a "me" problem.

    The answer would've been simple if it was just a case of setting async to false in the ajax query, but that's deprecated.

    The answer is: I give up, but only because it's probably unwise for multiple methods to rely on multiple ajax calls for their logic.

    So instead, I'm going to import the records from the json file into an array so I'll always have access to the data without this headache.


  2. Try like,

    function queryRecords(recordId, requiredField) {
      return new Promise((resolve, reject) => {
          $.ajax("javascript/records.json", {
            dataType: "json",
            success: function (response) {
              resolve(callBack(recordId, requiredField, response));
            },
            error: function (jqXhr, textStatus, errorMessage) {
                reject(errorMessage);
            }
        });
      });
    }
    
    function callBack(recordId, requiredField, response) {
      $.each(response, function(index, records) {
          if (records["MediaItemID"] == recordId) {
              $.each(records, function(key, value) {
                  if (key == requiredField) {
                      return value;
                  }
              });
          }
      });
    }
    queryRecords("14", "MediaItemName").then(response => {
      // response will contain your return value
    }).catch(errorMessage => {
      alert("AJAX error: unable to retrieve records from records.jsonnn" + errorMessage);
    });
    

    A sample implementation,

    function queryRecords(userId) {
    
          return new Promise((resolve, reject) => {
              $.ajax("https://jsonplaceholder.typicode.com/todos", {
                dataType: "json",
                success: function (response) {
                  resolve(callBack(userId, response));
                },
                error: function (jqXhr, textStatus, errorMessage) {
                    reject(errorMessage);
                }
            });
          });
        }
    
        function callBack(userId, response) {
          let filteredTodos = [];
          $.each(response, function(index, todo) {
              if (todo.userId == userId) {
                  filteredTodos.push(todo);
              }
          });
          return filteredTodos;
        }
               
        queryRecords(1).then(filteredTodos => {
          alert(filteredTodos);
        }).catch(errorMessage => {
          alert("AJAX error: unable to retrieve records from records.jsonnn" + errorMessage);
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search