This post will be a summary of what I learned from the Asynchronous JavaScript with async/await course from Marius Schulz on egghead.io. If you've never taken an egghead course before, its goes straight to the meat. No fluff just right in using the concept in practice.
To make a function asynchronous all we have to do is add the async
keyword(easy right?). By default regular JavaScript functions are not asynchronous meaning they wait there turn to run.
By adding the async keyword JavaScript can move on to another task while the function finishes. You can a make any type of function async.
The await keyword can only be used inside of a async function and it will pause the function until a promise is received. An async function is like a boomerang, when you send it out it always comes back with a promise. If the promise is rejected it you'll get a rejected value, if the promise is resolved you can store in a variable.
async function showGitHubUser(handle){
const url = `https://api.github.com/users/${handle}`;
const response = await fetch(url);
const user = await response.json();
console.log(user.name);
console.log(user.location);
}
One thing I thought was really cool about the await keyword is that you can use it to pause more than one request, and wait until they both are returned. You can do this by storing the promise that is returned in variables and awaiting the return of those variables.
This is better for performance you don't want a slow down of waiting for one request to finish then starting all the way over.
async function showUserAndRepos(handle) {
const userPromise = fetchFromGitHub(`/users/${handle}`);
const reposPromise = fetchFromGitHub(`/users/${handle}/repos`);
const user = await userPromise;
const repos = await reposPromise;
console.log(user.name);
console.log(`${repos.length} repos`);
}
The last thing that stuck out to me was the for await of loop. It's gives us the ability to loop over async objects asynchronously. A for await of loop also receives promises and wait for them to be resolved.
From having no prior experience with async/await I learned a lot about and would feel comfortable using in my own projects.
async function main() {
for await (const value of someGenerator()) {
console.log(value);
}
}
Now for a quiz! Try to recall the answers from memory!
An async function always returns a object? True or false
You can only make arrow function asynchronous? True or false
How do you make a function asynchronous?
A. By wishing it was
B. By adding the async keyword at the beginning of the function
C. By add the await keyword inside the function
How did you do?
Also here is a link to a repl.it I've made to show off the async function in action.
Top comments (0)