As a Java developer it speaks for itself that I’m using Java most of the time.
Recently I had to develop an AWS Lambda using Node.js.
I had a great time learning about JavaScript. I learned about promises, async/await and functional programming in JavaScript.
I created a small code-example below. This example will fetch some random Chuck Norris quotes for you. I filtered out quotes longer than 3 sentences.
Tutorial
If you wanna try it out, follow these steps:
- Open this website with Chrome
- Press F12 to open the Chrome Console
- Click on Console
- Copy the content of the script below and paste it in the Console you just opened
- Press Enter
- Wait and see. Your Chuck Norris quotes will soon appear.
async function fetchRandomChuckQuote() { let response = await fetch('https://api.chucknorris.io/jokes/random') let data = await response.json() return data } async function getArrayOfChuckQuotes() { let quotes = [] let range = [...Array(5).keys()]; for (let i in range) { let quote = await fetchRandomChuckQuote() quotes.push(quote) } return quotes } async function filterChuckQuotes() { array = await getArrayOfChuckQuotes() let filteredQuotes = [] array .filter(quote => { return quote.value.split(".").length < 3 }) .map(quote => { return quote.value }) .forEach(quote => { filteredQuotes.push(quote) }) console.log(JSON.stringify(filteredQuotes, null, 1)) } filterChuckQuotes()
Originally I foresaw some more error handling. To keep it simple you can take the code above and paste that in your console. The code below is just the original way of handling errors when the Chuck Norris api is down.
async function getArrayOfChuckQuotes() { let quotes = [] let range = [...Array(5).keys()]; for (let i in range) { let quote = await fetchRandomChuckQuote() quotes.push(quote) } return quotes } async function filterChuckQuotes(){ array = await getArrayOfChuckQuotes() let filteredQuotes = [] array .filter(quote => {return quote.value.split(".").length < 3}) .map(quote => {return quote.value}) .forEach(quote=> {filteredQuotes.push(quote)}) console.log(JSON.stringify(filteredQuotes, null, 1)) } filterChuckQuotes() async function fetchRandomChuckQuote(){ try { let response = await fetch('https://api.chucknorris.io/jokes/random') if (response.status.toString()[0] !== '2') { console.log('Something went wrong calling Chuck Norris : ' + response.text()) throw { response: { statusCode: 500, body: { message: 'Error while calling Chuck Norris api'} } } } const data = await response.json() return data } catch (error) { if (error.response) throw error console.log('Error fetching random chuck: ' + error) throw{ response: { statusCode: 404, body: { message: 'Error fetching randomChuckQuote'} } } } }
One thought on “JavaScript: async / await”
Nice one!