Issue
I have been having difficulties making a local variable a global variable. I am using Express and Javascript.
Here is my JavaScript code:
// Setting up Express and EJS
const express = require("express");
const JSON = require("JSON")
const app = express()
const fetch = require("node-fetch");
app.set('view engine', 'ejs');
app.use(express.static('Public'));
app.get('/',function (req, res) {
res.render('index', {price})
});
app.listen(3000);
// Link to the API
const url = "THE LINK"; // I have deleted the link from here because it has an API key along with it.
// Retrieving Data from the API
var price;
async function getData() {
const response = await fetch(url);
const data = await response.json();
price = data.c;
}
console.log(price) // Here I tried to log the price variable
Output:
undefined
Solution
You need to call getData()
inside the route that wishes to use the value. And, you need to return and use the value you get from that function correctly. Here’s one way to do it:
async function getData() {
const response = await fetch(url);
const data = await response.json();
return data.c;
}
app.get('/',function (req, res) {
getData().then(price => {
res.render('index', {price})
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
});
Note: In asynchronous code (which fetch()
is), you cannot assign a value to a higher scoped variable and then just use it anywhere. That code that wishes to use the variable will have no idea when it’s actually valid (when the asynchronous operation completed).