0

I have 2 HTTP requests, function call1() returns a variable I need to be used in function2(). The return value from call1() is defined however when call1() is triggered path in call2() it somehow become undefined.

call2(pageTitle); // call this function before call1()

function call1() {
    console.log('Before ajax call');
    var url = window.parent.__env.swaggerBaseUrl + 'api/Management/Configurations?name=ApiManagement';
    $.get(url).then(function(data) {
        if (data && data.Results && data.Results[0] && data.Results[0].Value) {
            console.log('If() I am here', data.Results[0].Value); // its defined
            return data.Results[0].Value;
        }
    })
}

function call2(pageTitle) {
    var path = call1();
    var url = path  + "Ewp/Definition?name=" + pageTitle.replace(/%20/g, ' ');
    console.log('EWP Data Path URL', url); // url is undefined
    $.get(url).then(function (data) {
        console.log('EWP Data in success', data);
        document.getElementById('xmlEWP').innerHTML = data.Results.Definition;
    })
}

Can someone point out why the return data.Results[0].Value is returning undefined in call2(). In my console.log() it fired call2() first which is correct according to the code above.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
MrNew
  • 1,384
  • 4
  • 21
  • 43
  • 1
    AJAX requests are asynchronous so you cannot return anything from them. Instead you need to work with the returned value within the callback function only. To fix your problem place `call(data.Results[0].Value)` in the callback of `$.get()` in `call1`. See the duplicate question I marked for more detailed information – Rory McCrossan Jan 09 '17 at 12:46
  • so I can't just do a return and call `call1()` in `call2()`? – MrNew Jan 09 '17 at 12:50
  • Oh nvm I totally missed the first line of your comment. Thanks – MrNew Jan 09 '17 at 12:53
  • No problem, glad to help – Rory McCrossan Jan 09 '17 at 13:02

0 Answers0