Promise API
new Promise()
new Promise((resolve, reject) => {})
const getDinosaur = (name) => {
return new Promise((resolve, reject) => {
resolve({name})
})
}
const getDinosaur = (name) => Promise.resolve({name})
const getDinosaur = (name) => Promise.reject(new Error("Dinosaurs went extinct!")
Promise.then
getDinosaur("Stegosaurus")
.then((dinosaur) => console.log(dinosaur))
.then()
coerces all returned values to a Promise
(chaining)
getDinosaur("Brontosaurus")
.then((dinosaur) => dinosaur.name)
.then((name) => console.log(name))
Promise.catch
- Handle errors with a
Promise
const getDinosaurs = () => Promise.reject("Connection Timed Out!")
getDinosaurs()
.catch((reason) => console.error(reason))
Promise.all
const getDinosaur = (name) =>
new Promise((resolve) =>
setTimeout(() =>
resolve({name, age: jurrasicPeriod()}),
Math.random() * 3000)
)
const jurrasicPeriod = () => Math.floor(Math.random() * 54e6) + 145e6
const log = (value) => console.log(value)
const dinosaurs = ['Brontosaurus', 'Tyrannosaurus', 'Stegosaurus']
Promise.all(dinosaurs.map(getDinosaur))
.then(log)