我正在尝试为我的 React 项目创建一个通用的 Fetch 方法。计划是向我的 fetch 方法传递一个 url 和一些配置数据(方法、 header 等)。然后向我的调用方法返回较少的技术数据。我想从 api 调用返回数据,以及有效负载,即 json 数据。
return fetch(URL, config)
.then((response) => {
console.log('Fetch - Got response: ', response);
return response;
})
.then((response) => {
console.log('Json: ', response.status);
const result = { data: response.json(), status: response.status };
return result;
})
.catch((e) => {
console.log(`An error has occured while calling the API. ${e}`);
reject(e);
});
这是我的初步尝试,但我不太确定我在做什么。
我的控制台日志记录了“响应”,包含来自 API 调用的响应:
body: (...)
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:49487//api/xxx/yyy"
API 调用完成,我得到 200 状态。
行:
console.log('Json: ', response.status);
按预期返回 200。
我之前一直在做的是
return response.json()
然后我的调用类获得了 Paylad,但没有状态。我想做的是返回我的有效负载和状态。
所以我尝试将其更改为:
const result = { data: response.json(), status: response.status };
return result;
但我的调用应用程序现在看到:
data: Promise {<resolved>: Array(9)}
status: 200
我期望获取数据:MyPayloadArray,状态:200
我认为我在这里误解了 promise 。 (我对他们很陌生)。
使用 Fetch 方法的数据访问器:
static GetAll() {
return new Promise((resolve, reject) => {
const request = {
method: 'GET',
URL: `${Server.ApiURL}/api/admin/clients`,
};
fetchData(request)
.then((result) => {
console.log('GetAll sees response as ', result);
resolve(result);
})
.catch((error) => {
reject(new Error(error));
});
});
}
我正在尝试调用我的数据访问器类,如下所示:
componentDidMount() {
ClientDataAccessor.GetAll()
.then((response) => {
console.log('Got list!', response);
this.setState({ clients: response, isLoading: false });
})
.catch((error) => {
console.log('Got error on list screen', error);
});
}
如何才能将状态和负载返回到我的 DataAccesor 类?我想我只是搞砸了 promise ......但不确定这里的最佳模式。
我要进入 UI 类,onComponentDidMount -> DataAccessor.GetAll -> FetchData。我认为我在某个地方滥用了 Promise。
最佳答案
这里的问题是 response.json()
返回另一个 promise 。您必须自己解析该 Promise 对象并返回您正在查找的对象。
return fetch(URL, config)
.then((response) => {
console.log('Fetch - Got response: ', response);
return response;
})
.then((response) =>
response.json()
.then( (data) => { data, status: response.status } )
)
.catch((e) => {
console.log(`An error has occured while calling the API. ${e}`);
reject(e);
});
太丑了...
为什么不将其移至 async/await 函数?现阶段所有浏览器都支持它...
async myFetch(URL, config) {
try {
const response = await fetch(URL, config);
console.log('Fetch - Got response:', response);
const data = await response.json();
console.log('Fetch - Got data:', data);
return { data, status: response.status }
}
catch (e) {
console.error(`An error has occured while calling the API. ${e}`);
throw e;
}
}
请注意,在这两种情况下,您的函数都会返回另一个 Promise。
关于javascript - 尝试从 fetch Promise 获取数据 'status',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52790523/