简体   繁体   English

处理从 fetch 返回的正确方法

[英]Proper way of dealing with returning from a fetch

I'm a bit new to coding in a JS/TS way and I just wanted to know the best practice when it comes to returning and handling void and values that come from a fetch.我对以 JS/TS 方式编码有点陌生,我只是想知道在返回和处理来自 fetch 的 void 和值方面的最佳实践。 In short, I'd like to use fetch to retrieve a JSON file somewhere, extract some relevant info, and return a dict.简而言之,我想使用 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 returns an error saying that Property 'name' does not exist on type 'void | {...} TS 返回一个错误,指出Property 'name' does not exist on type 'void | {...} Property 'name' does not exist on type 'void | {...} when I want to use the values of the dict. Property 'name' does not exist on type 'void | {...}当我想使用字典的值时。 The error, I completely understand.错误,我完全理解。 When using the function I try to do type checking to handle when it returns void, but it still raises an error for something like this:当使用该函数时,我尝试在它返回 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
    }
}

I'm just wondering what's the best way to write and handle void, and using the dict values.我只是想知道编写和处理 void 以及使用 dict 值的最佳方法是什么。

I wouldn't have the function do too much.我不会让这个功能做太多。 Have it concentrate on returning some data, and let the function that calls it deal with how that data is going to be used.让它专注于返回一些数据,并让调用它的函数处理如何使用这些数据。

If you're going to use async/await you should be consistent .如果你打算使用async/await 你应该是一致的。 Mixing async with then doesn't make a lot of sense.asyncthen混合并没有多大意义。 This way you're either going to return some data, or throw an error.这样你要么返回一些数据,要么抛出一个错误。

 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