As you have already been told, JavaScript works asynchronously , not sequentially like most of programming languages. It is for this reason that many callbacks are often used in this language.
Actually, the AJAX request you are making and the alert(num)
are executed in the same period of time. This is why the value of num
is undefined
.
Solutions
The solutions are not so broad, but the existing ones will serve us in a wide range of situations. Let's see some.
Make a synchronous AJAX request (your worst alternative): this solution is simply to add the async
key with a false
value in the parameters of the request:
let response = $.ajax({
type: 'GET',
url: 'destino',
async: false
}).responseText;
// añadiendo la variable a window se hace global
window.num = JSON.parse(response)[0];
Use a polyfill to make use of future language features: With the help of Babel we can make use of future JavaScript features as it is < a href="https://ponyfoo.com/articles/understanding-javascript-async-await"> Async / Await through this plugin :
let response = await $.ajax({ /* ... */ });
// o usando la API fetch
let response = await fetch({
method: 'GET',
body: { ... },
accept: 'application/json',
'Content-Type': 'application/json'
});
Namespaces
Using global variables is a bad idea . As your application / web grows and you add libraries / frameworks, the risk of a collision of variables increases, which increases the risk of malfunctioning and difficult debugging. Also, if misused, it could trigger a memory leak .
Using a namespace is a simple solution to this problem . A namespace is a space where different data related to each other is stored (as in C #). In JavaScript we do not have them natively, but we can emulate them by means of a global object that stores in the relative data. For example:
window.ventas = {
desc: 0.25,
iva: 0.18,
hacerAlgo() {
}
}
Here we have created a namespace that contains values and even a function that correspond to the sales namespace. While we add it to the global scope, it's much cleaner and safer to do it this way.