Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda