Variables in JS Node

Asked

Viewed 39 times

-1

wanted to understand more the concept of variables in NODE.
I tried to make a simple code to read a json from the internet.
I created a variable to receive the name of the title, but after set, it returns to the old value.
I’m starting now and wanted to understand more about how variables work on Node.

Thank you!

const express = require('express');
const request = require('request');

const app = express();

app.get('/', (req, res) => {
    let encryptTitle = 0
    request.get({
        url: 'https://my-json-server.typicode.com/typicode/demo/posts',
        json: true
    },
         (error, response, body) => {
            encryptTitle = body[1].title
            console.log(encryptTitle) // retorna Post 2
    });

    console.log(encryptTitle) // retorna 0
    res.send("Hello Worlds")
})


app.listen(3000);

1 answer

1

The variable is correct, the problem is that in Javascript IO (network, file, etc) tasks are performed asynchronously. The problem here is that the log that returns "0" is executed during the request. The log that returns "Post 2" is executed only when your request is completed, well after the log that returns 0 is executed.

The problem is related to the asynchronous part of Javascript and essential to master the language. I recommend reading the various ways to write this code, in general callbacks, Promises and async are used.

Good studies!

  • Do you have any suggestions for material for me to study? Or even the code working for me to look at?

  • The simple way would be to continue writing code inside your callback (there you have the return comment 2). The problem is that soon the code will be unmanageable and then worth looking at the forms I mentioned.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.