compose a POST type request using a PROMISE function

Asked

Viewed 321 times

0

I am a python programmer and I am programming now in javascript with Nodejs, I am already able to program normally but a doubt that is not letting me progress in the language is the issue of the precedents, I need to compose a request of type POST where it will be full-bodied the body that is the result of a trial, I thought to use the timeout but I believe that there are better outputs for this, I would like a help from you, I will leave an example below.

function composeBody(){
   const build = axios.get('www.exemplo.com/json')
   return build.json()
}

function sendPostRequest(bodyComposer){
   axios.post('www.sendpostrequest.com', {body: bodyComposer})
}

composeBody().then((r) => { sendPostRequest(r) })

the above code is merely illustrative, just like to understand how is the correct way to do this, send a request type POST with body, headers receiving the result of a function that will be a Promise. I know I could use one. then in the function and pass the Promise as parameter in the second function but I believe that when I have to compose a more detailed POST I will have problems. I read about await/async but I still can’t make it work as it should, who can help me I am very grateful.

  • Have you tried to start with Axios documentation?

  • 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.

  • If you want to understand how to chain asynchronous operations in Javascript, start by understanding what are callbacks. Then take a look at the Promises, which are most used nowadays.

  • 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 ;).

1 answer

1


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.

  • You understood my question perfectly, you were already aware of the problems with callbacks and the deficiency of time outs when it comes to flexible situations. Thank you for showing the right and no-brainer way to do this kind of chaining.

  • a question that I came to read your introduction, seeing the javascript nowadays is only used asynchronously, and of course for its advantages of performance I wonder: would it be possible to execute a request in a synchronous way? if yes as it would be, could you give me an example?

  • @Jeffersonmatheusduarte Well, we can perform a synchronous request. But for obvious reasons, which you recognize yourself, this is extremely contraindicated. Of course there are cases where it is preferable to execute a synchronous request rather than an asynchronous one, but this is rare (especially in the multilevel scenario we have today). PS.: I edited the above code with a title for synchronous requests.

  • 1

    thanks for clarifying, the questions I raised here were to better understand the logic with your explanation I already have knowledge necessary to add language to my range. Thank you so much for your attention and for the details in the explanations.

Browser other questions tagged

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