Home > Mobile >  How to run the second fetch function when the first one is finished with async, Javascript?
How to run the second fetch function when the first one is finished with async, Javascript?

Time:10-24

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)
}

CodePudding user response:

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))
 }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

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)
     }
    
  • Related