Self-Executing Functions
Fetch the latest currency conversion rate using async ... await
Search for a command to run...
Fetch the latest currency conversion rate using async ... await
No comments yet. Be the first to comment.
index.html : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Workers</title> <script src="main.js"></script> </head> <body> 1 USD = <span...
Taking advantage of latest JavaScript features: ECMAScript 2024

Replacing deprecated event.target.selectedIndex with this.selectedIndex

Using destructuring to update an object's attribute

JavaScript
12 posts
Let's say you wanted to call a function using await (let's call this function get_usd2inr) by calling it as in like - await get_usd2inr();, you may get this error:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at main.js:15:1)
We solve this using self-executing functions - ()(); with async.
let xe = 0;
const get_usd2inr = async () =>
{
const url = "https://open.er-api.com/v6/latest/USD";
try
{
const response = await fetch(url);
const data = await response.json();
const usd2inr = Number(data.rates.INR.toFixed(2));
return usd2inr;
}
catch (error)
{
console.error('Error fetching exchange rate:', error);
throw error;
}
}
// self-executing function
(async () =>
{
xe = await get_usd2inr();
console.log(xe); // 86.97 as of 13th February 2025
}
)();
console.log(xe); // 0 - at this point of time, get_usd2inr() is not yet done executing
In case you prefer a server-side fetch of open.er-api.com if at all they start blocking CORS all of a sudden :
def exchangerate_usd2inr():
url = "https://open.er-api.com/v6/latest/USD"
response = requests.get(url)
usd2inr = response.json()['rates']['INR']
usd2inr = round(usd2inr, 2)
return usd2inr
If you want to look into an example using workers check out a future blog post on using Google’s Comlink.