

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Synchronous vs. Asynchronous
incomplete
2: Why Async?
incomplete
3: Promises
incomplete
4: Why Promises?
incomplete
5: Await
incomplete
6: Async Keyword
incomplete
7: then vs. await
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
In the early days of web browsers, promises and the await keyword didn't exist, so the only way to do something asynchronously was to use callbacks.
A "callback function" is a function that you hand to another function. That function then calls your callback later on. The setTimeout function we've used in the past is a good example.
function callbackFunction() {
console.log("calling back now!");
}
const milliseconds = 1000;
setTimeout(callbackFunction, milliseconds);
The .then() syntax is generally easier to use than non-Promise callbacks, but async and await make handling promises even simpler. As a general rule, prefer async and await over .then and new Promise()... I mean for realsies, which of the following is easier to understand?
fetchRecipient()
.then(function (recipient) {
return fetchMessageForRecipient(recipient.id);
})
.then(function (message) {
return fetchDeliveryStatus(message.id);
})
.then(function (status) {
console.log(`The status is ${status}`);
});
const recipient = await fetchRecipient();
const message = await fetchMessageForRecipient(recipient.id);
const status = await fetchDeliveryStatus(message.id);
console.log(`The status is ${status}`);
The async and await keywords weren't released until after the .then API, which is why there is still a lot of legacy .then() code out there.