javascript · level 3 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A promise is an IOU: now, later.
fetch hands back a promise: an IOU for a value that is not ready yet. A promise starts pending. Later it is settled, exactly once: it either resolves with a value or rejects with an error. await pauses until it settles.
runs task after ms milliseconds, thousandths of a second. Put it inside and you have made your own promise. Call resolve(value) when the work succeeds or reject(error) when it fails.
function bakeCake(flavour) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (flavour === "") {
reject(new Error("No flavour chosen"));
} else {
resolve(`${flavour} cake`);
}
}, 100);
});
}
console.log("Oven on");
const cake = bakeCake("Lemon");
console.log(await cake); Gwecode lets you write await at the top level of your program, outside any function.
guess first
Three tries to settle one promise. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const answer = new Promise((resolve, reject) => {
console.log("working");
resolve("first");
resolve("second");
reject(new Error("too late"));
});
console.log("waiting");
console.log(await answer);
your turn
Your turn. Spot a fake ticket.
In the first blank, type the function that fails a promise. In the second, invent a ticket code without GW in it.
fix it
Hello, undefined? Can you fix it?
- What does
loadUserhand back straight away: the user, or something else? useris still a pending promise. Promises have nonameproperty.- Write
awaitbeforeloadUser(3)on line 6, then press run.
nailed it
you can make your own promises. :D
- A promise starts pending and settles exactly once.
- Call
resolvefor success andrejectfor failure. - Forget
awaitand you get the promise, not its value.
new words in your collection
- pending
- settled
- resolve
- setTimeout
This lesson isn’t saved. A free account remembers every lesson you finish.