Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
Error passing information within promises

I have three functions: [getLocation, getWeather, displayWeather]

I would like displayWeather to use async, and call the other functions, but i'm getting an error from getWeather(), stating something went wrong from reject().

I understand there's an issue somewhere getting lat, lon positions, but can't figure out where my issues are coming from.

Definitely new to JS Promises, and would love some support.

Thanks very much

import Card from "../Card/Card";
import { useState } from "react";

const WeatherCard = () => {
  const [location, setLocation] = useState([]); // array default

  const getLocation = () => {
    return new Promise((resolve, reject) => {
      // if location is enabled in browser
      if (navigator.geolocation) {
        // get [lat, lon] coordinates, passes to setLocation()
        resolve(
          navigator.geolocation.getCurrentPosition((position) => {
            // set location state to array [lat, lon]
            setLocation([position.coords.latitude, position.coords.longitude]);
          })
        );
        // if location isn't enabled in browser
      } else {
        // error message
        reject(console.log("Please enable location services"));
      }
    });
  };

  // takes in location [lat, lon] and returns weather data
  const getWeather = (lat, lon) => {
    return new Promise((resolve, reject) => {
      // if location state has values
      if (location.length > 0) {
        resolve(
          // get data from api (api key is in .env file)
          fetch(
            `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude={part}&appid=${process.env.REACT_APP_WEATHER_API_KEY}`
          )
            // parse data to json
            .then((res) => res.json())
            .then((data) => {
              // write weather data to console
              console.log(data);
            })
        );
        // if location state has no values
      } else {
        // error message
        reject(console.log("Something went wrong getting the api"));
      }
    });
  };

  // displays weather data to user (async function)
  const displayWeather = async () => {
    // get location
    await getLocation();
    //pass in location state [lat, lon] to getWeather()
    await getWeather(location[0], location[1]).catch((err) => console.log(err));
  };

  // rendered elements
  return (
    <Card>
      <div>{location}</div>
      <button onClick={displayWeather}>Click</button>
    </Card>
  );
};

export default WeatherCard;

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda