1

Trying to work with a JSON API object. I get the data back and pick out a bit and push it to an object called "rxcui". The first confusing thing is I cannot console.log(rxcui) from my browser, but if I make a new variable and use rx = rxcui, then I can use console.log(rx) in the browser to see the object.

The real problem is that when I take the rx object which has two strings of numbers in it and try to make it an array so that i can use .join on them, the code won't run. When tried, Object.values(rx) gives back an empty array. But if I go into the HTML code on chrome browser and type into the console the same line it works as intended and I am able to get the object, join it together, and make the string I want.

url_for_rxui.forEach((element) => {
      $(document).ready(function() {
        $.ajax({
            url: element,
            type: 'GET',
            success: function(returned){
              rxcui.push(returned.approximateGroup.candidate[0].rxcui);}
        });})})


rx = rxcui
concat_rxcui = Object.values(rx)
console.log(concat_rxcui)




rxcui_list = 'https://rxnav.nlm.nih.gov/REST/interaction/list.json?rxcuis=';
list_url = concat_rxcui.join('+')

rxcui_url_inter = rxcui_list + list_url
console.log(rxcui_url_inter)
      $(document).ready(function() {
        $.ajax({
            url: rxcui_url_inter,
            type: 'GET',
            success: function(returned){
              console.log(returned);}
        });})

This is from the browser console:

console.log(rxcui)
VM3952:1 Uncaught ReferenceError: rxcui is not defined
    at <anonymous>:1:13
(anonymous) @ VM3952:1
console.log(rx)
VM3999:1 (2) ["114228", "84815"]

Any insight would be so appreciated.

Austin
  • 103
  • 10
  • `rxcui` *isn't* defined in the code you show, and it looks to be a simple misunderstanding of async programming. Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this duplicates. – Dave Newton Jul 17 '20 at 21:16
  • Where are you trying to use it if **not** the browser, node.js, rhino, something else? – zero298 Jul 17 '20 at 21:17
  • Im opening the html file that calls this JS file. What works is inspecting the html page and typing in the console. – Austin Jul 17 '20 at 21:20
  • That's because the async operation completes while you're typing in the console. – Barmar Jul 17 '20 at 21:56

1 Answers1

1

The problem here seems to be that the ajax request is an asynchronous operation. It returns a promise and is not necesarily completed when the next line is called.

So if you have an ajax request like below you should make the apropriate calls iinside the success function and not after the ajax call.

$.ajax({
        url: element,
        type: 'GET',
        success: function(returned){
          rxcui.push(returned.approximateGroup.candidate[0].rxcui);
          //Here you should call operations you need to do after the ajax request is done
 })
Achtung
  • 682
  • 3
  • 16