I am creating a weather app using front end only (HTML, CSS, and JavaScript) using NWS (National Weather Service) API, Google JavaScript Library API, Google Places API, and Google Geocoding API. I have created two async functions getCoordinates(region)
, and getWeatherData(latitude, longitude)
The entire program works without imports and exports. However, when I try to import and export the functions, it doesn’t work. I am getting an error message
Uncaught (in promise) InvalidValueError…
with the Google JavaScript API library I am loading in the /html file where I use loading=async
in the URL. However, I have no problem with without imports and exports.
In the .html file, I changed from
<script type="type/javascript" src="index.js"></script>
to
<script type="module" src="index.js"></script>
I have not changed the Google JavaScript URL that I load as async defer .js file as the last line before body tag finishes.
Imports in index.js:
import getCoordinates from './location.js';
import { getWeatherData } from './weather.js';
Exports in location.js:
export default async function getDefault(region) { //code here }
Exports in weather.js
export async function getWeatherData(latitude, longitude) { //code here }
2
Answers
First of all, make the simple function an arrow function
}
and
}
If getDefault and getWeatherData are not default exports from their respective files, you should use curly braces when importing them.
However, if these functions are default exports, you would import them without curly braces:
I hope this will help you.
For problems that are most likely to come up while working on JavaScript ES modules, precisely during the execution of async functions, there is an order that might go wrong, especially if you are using third-party libraries, such as Google APIs. Here is how to implement this entire flow for importing and exporting async functions correctly so all your scripts work as expected:
HTML File:
Index.js
Location.js
Weather.js