0
APIs & Async · Promises
New technique
A promise of a value
When the mines say “your ore is coming”, that's a promise. It isn't ore yet, but you can plan what to do when it arrives.
A promise is an object that stands in for a value that may arrive later, or never: the result of a request, a timer, a file being read.
Before promises, async code passed callbacks: functions to call when the work is done. Each step had to live inside the callback of the step before it, so the code drifted further to the right with every step. This is called callback hell, and handling errors in it meant checking at every level.
Promises turn that pyramid into a flat chain you read top to bottom, with one place to catch errors.
// Callbacks inside callbacks…
getOre((ore) => {
smelt(ore, (bar) => {
forge(bar, (sword) => {
console.log(sword);
});
});
});
// …become a flat chain of promises
getOre()
.then((ore) => smelt(ore))
.then((bar) => forge(bar))
.then((sword) => console.log(sword));