我有两个函数从API获取数据。其中一个更新待办事项完成,另一个获取待办事项列表。目前UpdateAndFetch()
函数滞后,有时返回未更新的列表。
我该如何解决这个问题?
调用API的函数
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))
}
组件内部的函数
async function UpdateAndFetch(todo, groupId) {
const updateTodoCompletion = await TESTupdateCompletion(todo)
const updateTodoList = await TESTFetchTodosFromGroup(groupId, todos, groupName)
}
您必须始终返回一个fetch函数,否则它将不会将值传递给下一次异步调用。
为了能够一个接一个地执行函数,你可以在调用函数时这样做。
async function UpdateAndFetch(todo, groupId) {
Promise.resolve(() => updateTodoCompletiong(todo)).then(response => fetchTodosFromGroup(groupId,todos,groupName))
}
之后,您可以捕获错误。
你可以在这里阅读文档,javascript提供的是非常有用的。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
如果有任何问题,请留下评论。
没关系,我找到解决办法了。
-
将获取函数包装为返回值
// 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)) ) }
-
重构执行函数的函数
// delete the todo and fetch the list async function UpdateAndFetch(todo, groupId) { await updateTodoCompletion(todo) await fetchTodosFromGroup(groupId, todos, groupName) }