ES2107 has new methods for handling promises: async & await. Due to the asynchronous nature of Javascript, when I call an api, it will likely return the api data last, even if it is called at the beginning of the code. I’m taking this example from Colt Steele’s Advanced JS Bootcamp on Udemy.
- Return one movie from OMDB using async/await
This is a call to the omdb movie database to return info on the movie Titanic. As you can see, on line 1, I add the async keyword in front of ‘function’, and then on line 3 I add await in front of the api call. When I use await in front of the api call, it returns a promise with the status of ‘pending’ (line 11). Once the promise is resolved, the function then console.logs the movieData, and then the ‘all done!’ message.
async function getMovieDataAwait() { console.log('starting!'); var movieData = await $.getJSON('https://omdbapi.com/?t=titanic&apikey=thewdb'); console.log('movie data - ', movieData); console.log('all done!'); } // data returned to console // getMovieDataAwait() starting! Promise {<pending>} movie data - {Title: "Titanic", Year: "1997", Rated: "PG-13", Released: "19 Dec 1997", Runtime: "194 min", …} all done!
2. Return multiple movies from OMDB using async/await
If I am doing multiple async calls, I can use await Promise.all. As above, I add the async keyword in front of function. Then on line 2, instead of using await for a single api call, I can wrap multiple api calls in an array using Promise.all.
It prints out the plot of “This Disaster Artist”, a great film I just saw today, and “About a boy” which is one of my all-time favorite movies.
async function getMultipleMovieData(first, second) { let moviesList = await Promise.all([ $.getJSON(`https://omdbapi.com?t=${first}&apikey=thewdb`), $.getJSON(`https://omdbapi.com?t=${second}&apikey=thewdb`) ]); console.log(moviesList[0].Plot); console.log(moviesList[1].Plot); }; getMultipleMovieData('the disaster artist','about a boy') // OUTPUT - console.log(moviesList[0].Plot) - 'the disaster artist' When Greg Sestero, an aspiring film actor, meets the weird and mysterious Tommy Wiseau in an acting class, they form a unique friendship and travel to Hollywood to make their dreams come true. // OUTPUT - console.log(moviesList[1].Plot) - 'about a boy' A cynical, immature young man is taught how to act like a grown-up by a little boy.
3. Find github user with most followers from unspecified number of users
async function getMostFollowers(...usernames) { let baseUrl = "https://api.github.com/users/"; let urls = usernames.map(username => $.getJSON(baseUrl + username)); let results = await Promise.all(urls); let max = results.sort((a,b) => a.followers < b.followers)[0]; console.log(`${max.name} has the most followers with ${max.followers}`); return `${max.name} has the most followers with ${max.followers}`; }; getMostFollowers('jbhafner','colt','planetoftheweb') .then(function(topUser) { console.log(topUser) }); // OUTPUT Ray Villalobos has the most followers with 2882
3. Find Star Wars character from swapi.co
async function starWarsString(id) { let str = ''; let results = await $.getJSON(`https://swapi.co/api/people/${id}/`); str += `${results.name} is featured in `; let movies = results.films[0]; let moreResults = await $.getJSON(movies); str += `${moreResults.title}, directed by ${moreResults.director}`; let planetData = moreResults.planets[0]; let finalResults = await $.getJSON(planetData); str += `and it takes place on ${finalResults.name}`; return str; }; starWarsString(2) .then(function(character) { console.log('Star Wars Character - ', character); }); // OUTPUT Star Wars Character - C-3PO is featured in The Empire Strikes Back, directed by Irvin Kershnerand it takes place on Hoth