gpt4 book ai didi

javascript - fetch api .then 调用代码先于服务 .then 执行,这会导致未定义的数据

转载 作者:行者123 更新时间:2023-12-02 21:41:44 24 4
gpt4 key购买 nike

我的服务中有这个功能

function getBreeds() {
const requestOptions = {
method: "GET"
};

return fetch(`${config.apiUrl}breeds`, requestOptions).then(handleResponse);
}

function handleResponse(response) {
response.text().then(text => {
const data = text && JSON.parse(text)
if (!response.ok) {
const error = (data && data.message) || response.statusText
return Promise.reject(error)
}
return data
})
}

它在我的 vuex 商店中被调用

getBreeds({ commit }) {
commit("getRequest")

catService.getBreeds()
.then(
breeds => {
commit("getBreedsSuccess", breeds) // this line of code executed first even the api is not yet finish
console.log(breeds)
},
error => commit("getFailure", error)
)
}

发生的情况是,我的 vuex 商店中的 .then 比我服务中的 .then 更先被调用,这导致品种值变得未定义。如何解决这个问题?

最佳答案

您的 handleResponse 没有返回任何内容,因此 getBreeds 函数返回一个 Promise,一旦您收到 header ,该 Promise 就会解析 (fetch 解析之后的微任务),但在解析响应之前。

每当你有一个 Promise 时,你几乎总是应该等待返回它,除了发起者,以确保事物正确地链接在一起。改变

response.text().then(text => {

return response.text().then(text => {

这会将 .text() Promise 返回给调用者、getBreeds 以及 getBreeds 的调用者。

(如果没有的话,您还应该将 .catch 放在 catService.getBreeds 调用的末尾)

关于javascript - fetch api .then 调用代码先于服务 .then 执行,这会导致未定义的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60349981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com