Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
Passing a value from one request to another request in ReactJs

I need help because I couldn't use a separate function to generate the token - it gives out a promise, not a value. I was told that a value can only be used inside a function.

For each request, I generate a new token in the first request and then pass that token into the second request.

I tried making a separate function to generate the token, but fetch returns a promise.

As a result, I made such a big function and it works. Is there a way to make a separate function for the first request and pass the result to the second request?

The first token generation function is required frequently, while the second request is always different.

    fetch('/api/token', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ 'id': '5' }),
    })
    .then(response => response.json())
    .then(result => {

    fetch('/api/reviews', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + result.token,
      },
      body: JSON.stringify({ 'limit': 10 }),
    })
      .then(response => response.json())
      .then(result => {
          this.setState({ data: result.data });
      })

    })
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

create a function that return promise

async function getToken() {
   return await fetch('/api/token', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 'id': '5' }),
    })
        .then(response => response.json())
        .then(result => {
            return Promise.resolve(result.token);
        }).catch(error => {
            return Promise.reject(error);
        })
}


async function getReview() {
    const token = await getToken().then(token => {
        return token
    }).catch(error => {
        //handle error
    });
    fetch('/api/reviews', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token,
        },
        body: JSON.stringify({ 'limit': 10 }),
    })
        .then(response => response.json())
        .then(result => {
            this.setState({ data: result.data });
        })

}

i did not test this code but you get the idea

i will test and update my answer asap

about 4 years ago · Juan Pablo Isaza Relatório

0

Yes you can with async / await. It will allow you to lift the lexical scope of the API response from inside the .then "callback hell" and into the parent function scope.

Your separate function which fetches the token will return a promise, but then the requesting function will wait for the promise to execute and resolve before continuing.

async function fetchToken() {
  const response = await fetch('/api/token', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ 'id': '5' }),
  })
  return await response.json();
}

async function getReviews() {
  const response = await fetch('/api/reviews', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + result.token,
    },
    body: JSON.stringify({ 'limit': 10 }),
  })
  const result = await response.json();
  this.setState({ data: result.data });
}

Additionally, if the token call does not need to be made every time the reviews call is made, then you can memoize the value, and use that memoized value.

const tokenMemo = useMemo(async () => await getToken(), []);

async function getReviews() {
  const response = await fetch('/api/reviews', {
  // ...
      'Authorization': 'Bearer ' + tokenMemo,
  // ...
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda