Hello, good night. All right?
So, let’s go to a brief conceptualization before moving on to the hard coded:
Conceptualization:
Javascript is single thread And that means he reads and executes one instruction at a time synchronously. However there are ways to implement asynchronous behavior and make it wait for a return to be finalized to then give treatment on this data.
There are basically (general) three ways to implement asynchronous behavior, being they via callback, async/await and Promises (the first way turns out not to be as efficient because of an old problem known as callback Hell (nested callbacks hell)).
Understanding asynchrony:
To better understand how this works, think that Javascript went out executing the instructions that are in front of you in a procedural way and do not expect them to have any feedback to proceed with the execution (if expected, this would create a huge lag and performance problem in the browser/client).
When we implement asynchronous behavior we are saying that we want it to continue executing its procedural instructions normally, but in parallel remember to return to that past execution when it has an answer.
Why NOT USE THE TIMEOUT?
The timeout would be nothing performatic and much less useful to you, because you do not know the time that the request GET will lead back and would generate a lock on the application with the timing just to wait for the return of a response that you do not even know will return.
For this we will implement a Promise which will be consumed by a async Function and in this async Function we will treat the behavior of POST.
Hand on the code:
Creating the Promise:
function composeBody() {
// Cria um objeto de promise.
// Parâmetros resolve (retorno bem sucedido) e reject (retorno mal-sucedido).
return new Promise((resolve, reject) => {
// Executa a requisição GET.
axios.get('http://api.exemplo.com.br/repositories')
// Recebe a res (resposta da requisição).
.then(res => {
// Tente resolver o parse da resposta para JSON
// Se a resposta for undefined ou qualquer coisa diferente de um JSON o parse falhará e caíra no catch.
try {
resolve(res.json());
} catch (err) {
reject(err);
}
});
});
}
Creating the asynchronous function:
// Determino que deverá ser uma função assíncrona.
async function sendRequest() {
// Recupero o body executando nossa promise.
// O await determina que o runtime espere o resolve/reject da promise.
const body = await composeBody();
// Disparo a requisição com o body recuperado
// OBS.: a partir do ES6 propriedades de objetos com o mesmo nome da variável são autorreferenciados em chave e valor.
axios.post('http://mysite.com.br/addrepo', {
body
});
}
sendRequest();
Synchronous requests:
// Determino que deverá ser uma função normal.
function syncRequest() {
// Cria um objeto do XMLHttpRequest (construtor embutido do ambiente no browser).
const xhr = new XMLHttpRequest();
// Abro a requisição com o método open.
// Parâmetro 1: Tipo da requisição.
// Parâmetro 2: Url para onde a requisição será enviada.
// Parâmetro 3: Determino que minha requisição deve ser síncrona (async: false)
// Caso coloque para true a requisição se torna assíncrona via AJAX.
xhr.open('GET', './hello.json', false);
// Envio a requisição com o método send.
xhr.send();
// Verifico se o status da requisição foi 200 (sucesso).
// Se sim, mostro a resposta em formato raw text no console.
if (xhr.status === 200) {
console.log(xhr.responseText);
}
}
NOTE: To use this object in Node.js, you will have to install its library https://www.npmjs.com/package/xhr. Behaves a little differently on the Server-Side, but nothing absurd.
Have you tried to start with Axios documentation?
– Luiz Felipe
o Xios I only used as an example, I want to understand how to do something of the kind to know how to deal with chains of functions that depend on each other, by programming in synchronous language this is still a bit confusing for me.
– Jefferson Matheus Duarte
If you want to understand how to chain asynchronous operations in Javascript, start by understanding what are callbacks. Then take a look at the
Promise
s, which are most used nowadays.– Luiz Felipe
I already have theoretical and practical knowledge of the three solutions (callback, time out and Promise), what I needed was to see in practice the chaining with a kind of Pattern design because I wanted to see the right way to do it since I have experience with totally synchronous languages. the answer below has already removed all my doubts, anyway thanks for the tips ;).
– Jefferson Matheus Duarte