简体   繁体   English

无法使用 Javascript 和 Express 将局部变量设为全局变量

[英]Unable to make a local variable a global variable using Javascript and Express

I have been having difficulties making a local variable a global variable.我一直难以将局部变量变成全局变量。 I am using Express and Javascript.我正在使用 Express 和 Javascript。

Here is my JavaScript code:这是我的 JavaScript 代码:

// 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: Output:

undefined

You need to call getData() inside the route that wishes to use the value.您需要在希望使用该值的路由内调用getData() And, you need to return and use the value you get from that function correctly.而且,您需要正确返回并使用从该 function 获得的值。 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.注意:在异步代码(其中fetch()是)中,您不能将值分配给更高范围的变量,然后在任何地方使用它。 That code that wishes to use the variable will have no idea when it's actually valid (when the asynchronous operation completed).希望使用该变量的代码将不知道它何时实际有效(异步操作完成时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM