简体   繁体   中英

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. In short, I'd like to use fetch to retrieve a JSON file somewhere, extract some relevant info, and return a 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 | {...} Property 'name' does not exist on type 'void | {...} when I want to use the values of the dict. 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:

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.

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 . Mixing async with then doesn't make a lot of sense. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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