繁体   English   中英

处理从 fetch 返回的正确方法

[英]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 你应该是一致的。 asyncthen混合并没有多大意义。 这样你要么返回一些数据,要么抛出一个错误。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM