0

I am new to jquery and i am struggling to get array function return from jquery promise. The function return undefined, but i want array return. Anyone can give hit why i am getting undefined return ? thanks

var actualData = $.getJSON('https://opendata-download-metfcst.smhi.se/api/category/pmp1.5g/version/1/geopoint/lat/58.59/lon/16.18/data.json')

function getWinddirection() {
  let windValue = [];
  actualData.then(function(result) {
    $.each(result["timeseries"], function(i, Daydata) {
      for (var i = 0; i < Daydata.length; ++i) {
        if (Daydata[i].validTime.split("T")[1] == "12:00:00Z") {
          return windValue.push(Daydata[i].wd)
        } else {}
      }
    })
  }).then(function(windValue) {
    return windValue;
  })
}
Mike Cluck
  • 28,921
  • 12
  • 72
  • 85

1 Answers1

0

When you return windValue inside $.each you are not in scope function anymore.

At the end of your first then there is no return value for next promise, so windValue is undefined in second then.

You dont have to return windValue inside $each, you just have to finish your iteration, then return value for second then.

function getWinddirection() {
  //first change
  var windValue = [];
  actualData.then(function(result) {
    $.each(result["timeseries"], function(i, Daydata) {
      for (var i = 0; i < Daydata.length; ++i) {
        if (Daydata[i].validTime.split("T")[1] == "12:00:00Z") {
          //second modification
          windValue.push(Daydata[i].wd)
        } else {}
      }
    })
    //third modification
    return windValue;
  }).then(function(windValue) {
    return windValue;
  })
}
Cyril ALFARO
  • 1,516
  • 16
  • 34