How to access API data globally?

let dataset = [];
 fetch(coordinatelink)
    .then(response => response.json())
    .then(data => {
      // const coords = [{lat : data[0].lat ,
      // lon : data[0].lon
      // }];
      let lat = data[0].lat;
      let lon = data[0].lon;
      const link = "https://api.openweathermap.org/data/2.5/onecall?lat=" + lat + "&lon=" + lon + "&appid=" + appid + "&units=metric";
      return fetch(link);
    })
    .then(responce => responce.json())
    .then(data => {
      dataset = JSON.stringify(data["data"]);
  });
app.post("/searchloc", function(req,res){
  let iconurl = "http://openweathermap.org/img/wn/"+ dataset.current.weather[0].icon+"@2x.png"
  res.render("searchloc",{icon:iconurl });
})

When I run this code I get error TypeError: Cannot read properties of undefined (reading 'weather'), So how can I access weather data in searchloc post request?

[edit: as long as your version of Node is 14 or higher, ie it’s not an old version] Add the keyword await in front of the word fetch

Edit: also didn’t see you were making a query in the query. I would flatten out the logic here, something like:

const coordData = await fetch(coordinatelink).json();

const [lat, long] = [coordData[0].lat, coordData[0].lat];
const link = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&appid=${appid}&units=metric`;
const { data } = await fetch(link).json();
const dataset = JSON.stringify(data);

It says

   await fetch(coordinatelink)
                 ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules

Ah, sorry I haven’t used CJS modules in Node for a fair while, forgot it required actual JS modules (import foo from "./bar" rather than const foo = require("./bar")),

So with what you are using, to make what I posted work, simplest way is to wrap in a self-executing async function, eg:

(async () = {
  // Logic here
})();

Or you can use a set of async functions.

Otherwise you need to put the app.post call in another then, otherwise it will try to execute before the promise has resolved – this is how JS works

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.