sedkonny
sedkonny

Reputation: 11

Is the return type using .then different from without it?

My code works with the following:

export async function FetchAPI(props){
    const url = `www.website.com/${props}`
    let res = await fetch(url)
    let response = await res.json()
    return response
}

But when I try to clean up the code using better practices, I get error for the below code saying it is returning undefined.

export async function FetchAPI(props){
    const url = `www.website.com/${props}`
    fetch(url)
        .then((resp => {
          resp.json()
          return resp
     }))
}

Anyone understand the differences and how I can get the second one to work?

Upvotes: 1

Views: 90

Answers (1)

jfriend00
jfriend00

Reputation: 707836

The correct code for the .then() version is this:

export function FetchAPI(props){
    const url = `http://www.website.com/${props}`;
    return fetch(url).then(resp => {
        return resp.json();
    });
}

Is the return type using .then different from without it?

This fixed version would generate the same exact returned results as your await version with the same URL. Both would return a promise that would resolve/reject based on the results of the fetch and the JSON conversion of the body.

Note: URLs used in Javascript programming should contain the protocol as shown here.

I wonder why using thenable rather than async/await is better practice.

Async/await is a more modern syntax. When sequencing multiple asynchronous operations or branching based on asynchronous results, it is pretty much always simpler to write, read and debug with async/await than using .then().

When you just have a single asynchronous operation, you can sometimes just return that promise and using async/await doesn't necessarily provide any advantages. It's entirely up to the designer of the code which one to use - either can work just fine when written properly.

There are times when a simple .catch() is cleaner than putting a try/catch around the whole block too for localized error handling. Like many things with coding style, there's no absolute right and wrong, just opinions on what looks like the cleanest code.

Also, if you want your code to run in older Javascript environments that don't support async/await, then you may need to use .then() and .catch() or transpile your code to an older target.

For a related discussion see Async / await vs then which is the best for performance?.

Upvotes: 2

Related Questions