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

164
Visualizações
How to run the second fetch function when the first one is finished with async, Javascript?

So i have two functions that fetch data from the API. One of them updates the todo completion, and the other one fetches the list of todos. Currently the UpdateAndFetch() function lags behind, and sometimes returns the not updated list.

How can i fix this?

Functions that make API calls

let base = import.meta.env.VITE_API_BASE

// fetch the todos that belong to groupId
export async function TESTFetchTodosFromGroup(groupId, todos, groupName) {
  let url = `${base}/todos/group/${groupId}`
  fetch(url).then(async (response) => {
    const json = await response.json()
    todos.value = json.data
    groupName.value = json.message

    if (!response.ok) {
      return Promise.reject(error)
    }
  })
}

//
export async function TESTupdateCompletion(todo) {
  //
  let url = `${base}/todos/completion/${todo.todoId}`
  var requestOptions = {
    method: 'PATCH',
    redirect: 'follow',
  }

  fetch(url, requestOptions)
    .then((response) => response.json())
    .then((result) => console.log(result))
    .catch((error) => console.log('error', error))
}

Function inside the Component

async function UpdateAndFetch(todo, groupId) {
  const updateTodoCompletion = await TESTupdateCompletion(todo)
  const updateTodoList = await TESTFetchTodosFromGroup(groupId, todos, groupName)
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You always have to return a fetch function otherwise it will not pass the value to the next async call.

And in order to have the ability to execute the function one by one you can do this where you call your functions.

async function UpdateAndFetch(todo, groupId) {
Promise.resolve(() => updateTodoCompletiong(todo)).then(response => fetchTodosFromGroup(groupId,todos,groupName))
 }

after that, you can catch errors.

You can read the documentation here it is really very helpful what javascript provides. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

also if any questions leave a comment.

about 4 years ago · Juan Pablo Isaza Relatório

0

Nevermind, found how to fix this.

  1. Wrap the fetch functions to be a return value

     // fetch the todos that belong to groupId
     export async function fetchTodosFromGroup(groupId, todos, groupName) {
       let url = `${base}/todos/group/${groupId}`
       // you need to wrap the fetch into return so that the awaits would work !
       return fetch(url).then(async (response) => {
         const json = await response.json()
         todos.value = json.data
         groupName.value = json.message
    
         if (!response.ok) {
           return Promise.reject(error)
         }
       })
    
       // Promise.resolve('done')
     }
    
     //
     export async function updateTodoCompletion(todo) {
       //
       let url = `${base}/todos/completion/${todo.todoId}`
       var requestOptions = {
         method: 'PATCH',
         redirect: 'follow',
       }
    
       // you need to wrap the fetch into return so that the awaits would          work !
       return (
         fetch(url, requestOptions)
           .then((response) => response.json())
           .then((result) => console.log(result))
           // .then(() => TESTFetchTodosFromGroup())
           .catch((error) => console.log('error', error))
       )
     }
    
  2. Refactor the function that executes the functions

     // delete the todo and fetch the list
     async function UpdateAndFetch(todo, groupId) {
       await updateTodoCompletion(todo)
       await fetchTodosFromGroup(groupId, todos, groupName)
     }
    
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