所以我有兩個從 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)
}
uj5u.com熱心網友回復:
沒關系,找到了解決方法。
將 fetch 函式包裝為回傳值
// 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) }
uj5u.com熱心網友回復:
您始終必須回傳一個 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
此外,如果有任何問題,請發表評論。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/336594.html
標籤:javascript 接口 异步等待 拿来
