0

I'm just updating my knowledge and understanding of some things in the JS world. Can someone please tell me if there is any difference between the following.

A nested promise nightmare

// Nested nightmare
fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(json1 => json1.json())
    .then(res1 => {
        console.log("======== 1 ======")
        console.log(res1)
        fetch(`https://jsonplaceholder.typicode.com/todos/${res1.id+1}`)
            .then(json2 => json2.json())
            .then(res2 => {
                console.log("======== 2 ======")
                console.log(res2)
                fetch(`https://jsonplaceholder.typicode.com/todos/${res2.id+1}`)
                    .then(json3 => json3.json())
                    .then(res3 => {
                        console.log("======== 3 ======")
                        console.log(res3)
                    })
            })
    })

Async await

// Using async await
const getData = async (id) => {
    return await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
        .then(json => json.json())
        .then(res => res)
}
const res_1 = await getData(1).then(res => {
    console.log("======== 1 ======")
    console.log(res)
    return res
})
const res_2 = await getData(res_1.id + 1).then(res => {
    console.log("======== 2 ======")
    console.log(res)
    return res
})
const res_3 = await getData(res_2.id + 1).then(res => {
    console.log("======== 3 ======")
    console.log(res)
    return res
})

EDIT: I should mention, that the result of each is reliant on the response from the previous. And the result of the first is needed for a comparison from the result of the last

  • 2
    "*A nested promise nightmare*" because that's NOT how you're supposed to use promises. – VLAZ Mar 13 '20 at 07:07
  • In the way it works, there's barely any difference, though the async/await is easier to read and understand. – Baruch Mar 13 '20 at 07:07
  • 1
    And your "Async await" code is also using promises incorrectly because when you use `await` you don't need to use `then`. – Dai Mar 13 '20 at 07:07
  • @Dai He's probably using it for the console log. – Baruch Mar 13 '20 at 07:08
  • @Baruch which is still unneeded `await promise; console.log()` is still equivalent and preferred instead of mixing. – VLAZ Mar 13 '20 at 07:08
  • @Baruch In that case the logging code could be refactored-out an invoked by-name instead of using a lambda. – Dai Mar 13 '20 at 07:09
  • Also useful: [Aren't promises just callbacks?](https://stackoverflow.com/q/22539815) – VLAZ Mar 13 '20 at 07:40

1 Answers1

0

Your nested nightmare can be rewriten as:

fetch('https://jsonplaceholder.typicode.com/todos/1').then(json1 => json1.json())
.then(res1 => {
    console.log("======== 1 ======")
    console.log(res1)
    return fetch(`https://jsonplaceholder.typicode.com/todos/${res1.id+1}`).then(json2 => json2.json());
}).then(res2 => {
    console.log("======== 2 ======")
    console.log(res2)
    return fetch(`https://jsonplaceholder.typicode.com/todos/${res2.id+1}`).then(json3 => json3.json());
}).then(res3 => {
    console.log("======== 3 ======")
    console.log(res3)
});

Which doesn't look much of a "nightmare" and shows better the equivalence between both things.

Jaime Blázquez
  • 349
  • 1
  • 9
  • Would even look better with an helper `fetchAsJSON = ( url ) => fetch( url ).then( resp => resp.json() );` *(and maybe even an other to generate the url if they really all share the same baseURI)* – Kaiido Mar 13 '20 at 07:34
  • 1
    Anyway, the main difference between promises and async/await, to me, is how it handles `try`/`catch`: with Promises if the first invoked function in a chain throws, you must catch it with `try`/`catch`, but if it happens in the chain, it will be catched with the second parameter of `.then` or with `.catch` (You can start the chain with `Promise.resolve()`, but that feels strange to me). With async/await there's no such difference. I like Promises for now because I don't have to think so much about backwards compatibility (there are libraries). – Jaime Blázquez Mar 13 '20 at 07:42