-2
function getEvents(userid,year,week) {
    var items = [];
    var path = "js/test.json";
    $.getJSON( path).done(function( data ) {
        items = data.sessions;
    });
    return items;
}

var list = getEvents(10,1991,13);

Here is my javascriot and I need to get an array to return from getEvents() method.

Isuru Herath
  • 298
  • 6
  • 20
  • 3
    You can't just return the data, because it arrives asynchronously. You need to use some async way to get the data back to the caller, either a callback or a promise. Read up on async execution in javascript. – doldt Mar 10 '15 at 08:43

1 Answers1

1

You should put the return statement inside the .done function as following:

function getEvents(userid,year,week) {
    var items = [];
    var path = "js/test.json";
    $.getJSON( path).done(function( data ) {
        items = data.sessions;
        return items;
    });
}
lvarayut
  • 13,963
  • 17
  • 63
  • 87
  • 1
    I did that. but list remains undefined. – Isuru Herath Mar 10 '15 at 08:55
  • 2
    -1. This "return" returns to the getEvents function body (where there's no control flow anymore), not to the call of getEvents (the list variable in OP), which was supposed to be the outcome. – doldt Mar 10 '15 at 09:16