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