Hint
Pay attention to how the optional chaining and nullish coalescing operators are used to handle cases where properties are missing or null
function fetchUserData() {
return Promise.resolve({ id: 1, name: 'John Doe' })
}
function fetchOrderData(userId) {
return Promise.resolve([{ id: 101, total: 100 }, { id: 102, total: 200 }])
}
fetchUserData().then(user => {
const orderId = user?.orders?.[0]?.id ?? 'No orders found'
console.log(orderId)
return fetchOrderData(user.id)
}).then(orders => {
console.log(orders)
const total = orders?.[0]?.total ?? 0
console.log(total)
})No orders found
[ { id: 101, total: 100 }, { id: 102, total: 200 } ]
100