1

I am new to JS an jQuery. And I am trying to build a key-value map from an API call which returns an array of key-value pairs.

[{"key":"191","value":244}, ... , {"key":"920","value":130}]

I came up with this ajax code. But following code will need the map constructed from loadMap. How to change it to non-ajax way that the "followingFunction" runs after loadMap finishes>

var mp = {};
(function loadMap() {
    $.ajax({
        type: 'GET',
        url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
        dataType: "json",
        success: function(arr){
            var out = "";
            for(i = 0; i<arr.length; i++) {
                mp[arr[i].key] = arr[i].value;
            }
        }
    }); 
}());

//followingFunction which needs the information from mp
4
  • Any reason you don't just use followingFunction in the success callback? Commented Mar 8, 2015 at 5:06
  • Thx for reply! I tried this but somehow doesn't work. And there are lots of stuff following, it seems ugly to put all those in success. Commented Mar 8, 2015 at 5:12
  • I was just wondering how to call a api the non-ajax way? Commented Mar 8, 2015 at 5:13
  • answer below - you can use the async flag. it is by default set to true - just set it to false and it will be a blocking call. Commented Mar 8, 2015 at 5:14

1 Answer 1

1

You can solve this in two different ways.

1) ExecutefollowingFunctionat the end of your success callback:

var mp = {};
function loadMap() {
    $.ajax({
        type: 'GET',
        url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
        dataType: "json",
        success: function(arr){
            var out = "";
            for(i = 0; i<arr.length; i++) {
                mp[arr[i].key] = arr[i].value;
            }
            followingFunction();
        }
    });
};
loadMap();

2) Set the async flag to false (by default this flag is true). This will result in blocking call with synchronous execution:

var mp = {};
function loadMap() {
    $.ajax({
        type: 'GET',
        url:'http://localhost:8080/xxx/api?start_date=2014-10-01&end_date=2014-11-01',
        dataType: "json",
        async: false,
        success: function(arr){
            var out = "";
            for(i = 0; i<arr.length; i++) {
                mp[arr[i].key] = arr[i].value;
            }
        }
    });
};
loadMap();
followingFunction(); 
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.