[英]Proper way of dealing with returning from a fetch
我對以 JS/TS 方式編碼有點陌生,我只是想知道在返回和處理來自 fetch 的 void 和值方面的最佳實踐。 簡而言之,我想使用 fetch 在某處檢索 JSON 文件,提取一些相關信息,並返回一個 dict。
async function doSomething() {
const response = fetch(...)
.then(response =>
response.json().then(data => ({
data: data,
response: response.ok
}))
)
.then(data => {
if (!data.response) {
console.warn("Response was not ok...")
return null
} else if (data.data["results"] == 0) {
console.info("Returned no results")
return null
} else {
const returned = {
name: data.data["stuff"],
thing: data.data["other"]
}
return returned
}
})
.catch(error => console.error(`${error}`))
return response
TS 返回一個錯誤,指出Property 'name' does not exist on type 'void | {...}
Property 'name' does not exist on type 'void | {...}
當我想使用字典的值時。 錯誤,我完全理解。 當使用該函數時,我嘗試在它返回 void 時進行類型檢查以處理,但它仍然會引發如下錯誤:
const request = await getQuery("movie", query)
if (request === undefined || request === null) return "I wasn't able to find your query."
const data = {
name: request.name
}
}
我只是想知道編寫和處理 void 以及使用 dict 值的最佳方法是什么。
我不會讓這個功能做太多。 讓它專注於返回一些數據,並讓調用它的函數處理如何使用這些數據。
如果你打算使用async/await
你應該是一致的。 將async
與then
混合並沒有多大意義。 這樣你要么返回一些數據,要么拋出一個錯誤。
async function getData(endpoint) { try { const response = await fetch(endpoint); if (response.ok) { const { data } = await response.json(); return data; } else { throw new Error('Response error.'); return undefined; } } catch (err) { console.warn(err); } } async function main() { const endpoint = 'http://example.com'; const data = await getData(endpoint); if (data && data.results) { console.log(data.results.name); } else { console.warn('No results'); } } main();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.