Promise
A Promise represents the eventual completion (or failure) of an async operation.
States
- pending — initial state
- fulfilled — operation succeeded
- rejected — operation failed
Creating a Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true
if (success) {
resolve('Data loaded!')
} else {
reject(new Error('Something went wrong'))
}
}, 1000)
})
Consuming Promises
promise
.then(result => console.log(result)) // 'Data loaded!'
.catch(error => console.error(error))
.finally(() => console.log('Done')) // always runs
Promise.all
const p1 = fetch('/api/users')
const p2 = fetch('/api/posts')
const p3 = fetch('/api/comments')
Promise.all([p1, p2, p3])
.then(([users, posts, comments]) => {
// all three resolved
})
.catch(err => {
// any one rejected
})
Promise.allSettled
Promise.allSettled([p1, p2, p3])
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log(result.value)
} else {
console.log(result.reason)
}
})
})