3

I'm fairly new with ES6 (used to work that part with Jquery and the so called callback hell). I got this code (working):

    feti(api_login, tudo);

    function feti(caminho, dados) {
      fetch(caminho, {
      method: 'POST',
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(dados)
      })
      // captura o erro 
      .then(erroAPI)
      // converte o sucesso em JSON
      .then(response => response.json())
      // disponível para uso
      .then((data, outraFunc) => {
        resposta = data.qscoluna;
        porTod(resposta);
      });
    }
    
    function porTod(valor){
      let api_login_suc = valor[0];
      salvaTudo(api_login_suc);
    }

First function is the one using fetch (feti), and the second one uses the response from first function (porTod).

In my site, I use lots of API calls, so I would like to make the "feti" function an reusable function. The question is: how can I make it acessible from a second function, without calling the second function inside the first (as I'm doing right now?)? If i just try to return the result from fetch and use it in the second function, I got a undefined response, as expected. I believe some kind of promise would be ideal, but I couldn't find any similar question to my problem, and I'm stuck. If someone can point me in the right direction, it would be nice. Just an "search this" would help a lot!

1 Answer 1

2

Just return the promise that you want to have processed:

function feti(caminho, dados) {
  return fetch(caminho, {
    method: 'POST',
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(dados)
  })
  // captura o erro 
  .then(erroAPI)
  // converte o sucesso em JSON
  .then(response => response.json())
}

Then instead of calling only feti(api_login, tudo); do

feti(api_login, tudo).then(data => {
  const resposta = data.qscoluna;
  porTod(resposta);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.