One place for hosting & domains

      How to Write a Blog Post: A Step-By-Step Guide


      1997: the year the Pathfinder landed on Mars, Madeleine Albright was sworn in as Secretary of State, and Titanic demolished box office records.

      It’s also the year the term “weblog” was officially coined (even though the first blog is said to have existed in 1994, at the near genesis of the internet). For two decades, starting a blog has been a powerful way to connect with internet audiences and share creative content.

      Yet, with blogging’s established rep as a powerhouse (and dominant) form of web content, it’s easy to witness the ever-changing and ephemeral landscape of the internet. Blink and virtual crowds have abandoned one novelty social media platform for another. Viral memes and web fads frequently give internet audiences virtual whiplash. Content creators are fighting to garner the ever-depleting attention spans of web users.

      So are the web’s 31.7 million blogs losing relevance anytime soon?

      Not at all.

      It turns out 77% of internet users read blogs regularly. What’s more, 61% of Americans spend three times the amount of time-consuming blog content than they do email content.

      Blogging is still very much a crucial part of a thriving brand and a next-level content marketing strategy in 2020. Whether you’re a brand or a business, you want to attract traffic and offer something of value to visitors. Blogging is a major key to that engagement — having a blog on your website increases your chances of ranking higher in search engines by a massive 434%. Plus, bloggers wield immense influence on the web — giving your brand the opportunity to grow in a big way.

      So do you have everything you need to be a blogging success? Let’s find out. Passion? Check. Website? Check. Fueled by a great *ahem* web hosting company *ahem*? Double-check. You’re ready to share your own unique content with the world wide web.

      Power Your Blog with DreamHost

      We’ll make sure your blog is fast, secure and always up so your visitors can engage with you. Plans start at $2.59/mo.

      OK, wait. How do you write a blog post? If you want to create value for readers and attract traffic to your site, it’s not as easy as typing up a few sentences in haste and clicking Publish. No, writing a great blog post requires creativity and smart crafting. And with the abundance of bloggers and the influx of ideas out there, you need to be at the top of your blogging game to cut through the noise and get eyes on your content.

      But don’t worry!

      We’re here to help. This everything-you-need guide covers it all: the reality behind blogging (aka vital stats to know), the ins-and-outs of crafting a great blog, and what handy resources are available to help with every aspect of writing your article.

      Dig in and study it word-for-word or just jump to the sections you need:

      Before we dive in too deep, let’s address something really fundamental: Why is writing a good blog post so important? Why does it even matter?

      So glad you asked (we love this topic)!

      Why Does Writing a Great Blog Post Matter?

      So what difference does a quality blog post make anyway?

      Well, the difference between a so-so blog post and a can’t-stop-reading blog post is a matter of only a handful of factors, but they’re crucial.

      An exceptional blog post not only helps attract your target audience to your site, but it helps establish you as an authority in your field and motivates visitors to continue engaging with you.

      In fact, 30% of people rank quality content as the top factor that adds credibility to a blog, so not only do you need to start a blog, you need excellent blog content. As you provide valuable content, readers will be more likely to develop loyalty to your brand. They’ll share your content with their friends, and trust us, social shares are the virtual word of mouth you need to flourish online.

      If you want authentic growth, you need killer blog posts.

      What Makes a Good Blog Post?

      So let’s break it down. What makes a perfect blog article? Here are the nine key ingredients.

      1. Targeted Message

      Or, in other words, Know Thy Audience. Ideally, you already know who you’re trying to reach with your brand or business.

      Similarly, your blog posts should be geared toward reaching and influencing a particular target audience — your specific niche — and addressing their needs. With a focused target, you are more likely to connect with audiences and build your brand. Casting an overly-wide net with your message will cause you to miss out on the key audiences that are most important for the growth of your brand.

      Valentine's Day post from House That Lars Built
      Brittany Jepsen of House That Lars Built knows her audience — creative DIY crafters — and tailors content for them.

      2. Clever Headline

      Your headline is often the make-it-or-break-it factor between someone clicking on your blog post or passing it by for some other site (likely a competitor’s content!)

      Your headline should grab readers, make them want more — tease and tantalize! — while still giving them a roadmap for the journey you’re going to take them on as well as an idea of what prize they’ll earn by adventuring. Invest the time to craft a good headline — it makes a big difference. Choose each word carefully.

      Pro-tip: Use a headline analyzer tool to get insight into the efficacy of your title and ways to improve.

      Behind-the-scenes blog post of Disneyland happenings.
      The author of this Disney Food Blog post entices readers with a behind-the-scenes look at Disneyland happenings.
      Blog post from At One Good Thing by Jillee.
      At One Good Thing by Jillee, this headline explains that the post will address a very common pain point — needing room-temperature ingredients in a pinch.
      Example of blog title using numbers.
      Using numbers is a solid way to quantify what value you’re offering to readers, like this post on author K.M. Weiland’s writing blog.

      3. Interesting Intro

      Kudos! You got a reader to click on your post, interested in finding more about your topic. Now — how to keep them reading (and keep your bounce rate steady)?

      You need a hook. You need to start your blog post with a captivating intro to draw the reader into your post. Whether you lead with a shocking stat, an engaging anecdote, a thought-provoking question, or an innovative idea, make your intro so compelling that your visitors can’t stop reading. Lure them in and hook ‘em.

      But take note — the introduction needs to satisfy the intent you hinted at in the headline or your audiences (and search engines) will punish you with lower traffic and rankings.

      Example of intriguing blog post intro.
      This post from Greatist hooks readers with an unexpected, intriguing intro.

      4. Valuable Content

      What does your blog post offer audiences? Readers are more likely to read and engage with your blog content if it offers them something of value, addresses a burning question, or solves a particularly deep pain point. Are you providing them with info they can’t find anywhere else? Is your content exclusive, comprehensive beyond your competitors, or outfitted with freebies or rich resources? Does it solve a problem?

      If so, then you’re on the right track.

      Let’s spend some time on this. Great blog posts are really all about understanding your audience — what they need, what they care about, how they behave. This type of research is crucial. Get to know them by reaching out to them, soliciting feedback, and asking questions. Get to know them and show you care.

      Next, do some internet research. Look at what people are searching for, what types of questions they’re asking (Google Auto-Complete anyone?). Browse Reddit, scout out competitor sites, and read comments.

      Simply put: Do your homework.

      Based on the intel you gather, develop a list of blog posts and content ideas that address the needs of your audience. You can start out with broad topics and then narrow the scope as you hone in on your niche. Plan what you need to distinguish your blog and beat out competitors in what you’re offering audiences.

      Popular content on the CSS-Tricks blog.
      The blog at CSS-Tricks clues readers into popular content and entices with the promise of answering a burning question.

      Need ideas on what kind of content to offer? Here are some well-received examples:

      • Listicles
      • Roundups
      • How-Tos/Tutorials
      • Exclusive Insights/Behind-the-Scenes

      5. Captivating Stories

      Visitors are more likely to connect with content that is relatable, human, and engaging, so gather your readers around the campfire (metaphorically, of course) and share relevant, captivating tales.

      Example of captivating story from Expert Vagabond blog.
      This post from Expert Vagabond hooks readers immediately with a captivating story.

      6. Easy-to-Scan Text

      Here’s an important stat for you. The average person spends only 37 seconds reading a blog post. If your text is long and clunky, it could be even less.

      Make your content easy to consume, organizing your snackable text in bite-sized pieces that’s easy to digest.

      Break up text into short paragraphs often, guided by informative subheads, emphasized text, and bullet points. Vary the length of your sentences, and utilize white space to provide visual breaks for readers’ eyes. Making text easier to read with consistent and organized formatting will help keep eyes on your content.

      7. Thoughtful Design

      It’s not just the content of your blog post that matters. Design (and blog structure) plays a big part in getting audiences to consume your content and engage with your brand. Pairing strong content with aesthetically-pleasing design makes your blog post that much more impactful.

      Thoughtful design includes smart use of white space, an attractive color scheme, easy-to-use navigation and menus, and other guiding design elements like leading lines and composition.

      It should also take into account the typical f-shaped scanning pattern when laying out design elements.

      Joi Knows How blog color scheme.
      The blog at Joi Knows How is united by a cohesive color scheme and engaging design elements, and thoughtful navigation.

      8. Authentic Writing

      The quickest way to turn off your audiences? Write content for them in an inauthentic voice. Visitors to your site don’t want salesperson speak, overly-technical jargon, academic mumbo-jumbo, or an unapproachable narrator — they want YOU. Your real, one-of-a-kind voice will keep them coming back for more.

      Example of relatable blog copy.
      Jessica of How Sweet Eats brings appeal to her blog posts not just by sharing delicious recipes and food photos — her writing feels real, relatable, and fun.

      9. Mobile-Responsiveness

      Mobile is king. Mobile internet usage has grown exponentially in the last few years, now dominating its share of traffic over desktop usage.

      Plus, more than five million people have smartphones, meaning that if audiences can’t access your blog post on mobile (or if your post isn’t responsive or attractive on their phone or tablet), they’re likely to hop to a competitor’s site.

      Prioritize a mobile-friendly blog to grow your brand. Use Google’s Mobile-Friendly Test to test out your site for possible responsiveness issues (this includes keeping things speedy!).

      Be Awesome on the Internet

      Join our monthly newsletter for tips and tricks to build your dream website!

      How to Write a Blog Post (In 6 Steps)

      Now, it’s time to write that blog post! Let’s get down to the nitty-gritty and do this step by step.

      1. Plan

      First, you need to sit down and prep your post. Planning is imperative to crafting a home-run blog post, especially if you want to stand out amongst your competitors and garner the attention you need.

      First off, you need to get yourself organized. Keep a running list of post ideas based on the research you’ve conducted on your audience and on valuable keywords. Brainstorm and mind map your thoughts. When planning your content calendar, consult your ideas and choose what would be the most useful for your target audience.

      Once you’ve settled on a winner, use a blog planner (like this one) and map out your topic. Create an outline with basic points and conduct the necessary research to flesh out important details. Visitors can get fake news anywhere on the web, so you owe it to your audience (and your brand) to only plan and create well-researched, high-value posts.

      And remember, it’s great to have a lot of content — more blog posts will draw more traffic. BUT. Make sure you’re prioritizing quality content over mere quantity and that you’re passionate about what you’re writing about.

      If you are, it will be evident — and contagious.

      2. Craft a Headline

      Your headline is crucial, remember? It’s got to be strong, or it’s not going to draw readers in.

      Remember: you want to entice and hint at what readers are going to get out of clicking on your article instead of someone else’s. A few headline pointers:

      • Optimal headline length is 11-14 words, both for social shares and search engine efficacy.
      • You need a captivating hook, plus enough info that your readers know what to expect and what value you’re offering them. Don’t just use throwaway clickbait phrases or pack in keywords. Trim the fat and use each word with intention.

      3. Write Your Post

      Time to start tickling those virtual ivories — meaning, it’s time to start writing your blog post. The average time spent writing a blog post has been increasing, so give yourself enough time (at least a few hours) to get your thoughts down and fully engage the writing process.

      The optimal length for blog posts is 2200-2500 words, so keep an eye on word count as you write. For now, don’t worry about making it perfect on the first go-around. Just keep those fingers moving and get the words down.

      Make sure to include a CTA (Call to Action) as you wrap up your post — you want your readers to be motivated to do something. And if they’ve stuck with you through a whole blog post, there’s a good chance they will.

      4. Find Images

      A blog post without images earns a big whomp, whomp, whomp — and gets little interest from readers and higher bounce rates. Blog articles with images get 94% more views.

      This means images — relevant, good quality ones — are absolutely necessary for your posts.

      DIY some of your own photography, get proper photo permissions for others’ work you want to share, or use a royalty-free site like Pexels or Unsplash to add images to your post and edit as necessary.

      You can also consider including alternative elements like infographics, charts, and graphics to create unique visual interest.

      Example of eye-catching image on Our Travel Passport blog.
      Eye-catching images are a hallmark of the Our Travel Passport blog, drawing readers in with visual interest.

      5. Edit Your Post

      Wait! Before clicking Publish, you need to edit your post. And no, a simple run of your standard-issue spell check isn’t enough.

      Here are some editing best practices:

      • Take a Break. Polish your post by stepping away from your keyboard for a time, then returning later with a fresh pair of eyes. The break will help you see errors you might have missed before.
      • Play Editor. Proofread your post with a fine-tooth comb and correct any grammar and spelling errors. Also take the opportunity to edit your text for clarity.
      • Think Syntax. The same type and length of sentences can get really boring — and difficult — to read. Vary your sentence length to keep things interesting.
      • Pack a Punch. Flimsy, weak-sounding copy turns off readers and leaves them unsatiated. Eliminate weak verbs and passive voice. You want your words to be strong and meaningful.
      • Get a Sounding Board. Read your text aloud to ensure it flows smoothly and sounds authentic and on-brand. Have a friend or colleague read over it and give feedback for an outsider’s perspective.
      • Fix Formatting. Make sure your text isn’t wonky when published. Preview it to ensure that it looks the way it’s supposed to — professional and well laid-out — providing plenty of visual space for eye breaks.

      Your blog content is a representation of your brand, so make sure it reflects a professional and polished image.

      6. Promote Your Post

      If you’ve followed the steps above, you’ve likely got a great blog post on your hands. That’s all fine and good, but if no one sees it, all your hard work is for naught! You’ll need to put in the content marketing legwork to get your post in front of your audience.

      Whether you use social media promotion, email marketing, paid advertising, or search engine optimization — ideally, a balance of all of these tactics — work to promote your post in ways that make sense for your target audiences.

      Helpful Blog Post Resources

      Don’t worry. We’re not done yet! We’ve got a handy-dandy toolbox of resources to help you make writing blog posts easy (and fun) — and above all, to help you build a successful blog and grow your brand. We know starting and maintaining a blog isn’t easy, but we’re here to help.

      Here are some super useful tools for each step of the writing process.

      Building a Website

      Planning

      Writing

      Editing

      Promotion

      The Final Word on Starting a Blog

      Ready to craft some kick-butt blog posts? You’ve got everything you need to write great posts; now you need to team up with a great web host.

      We’ve got you covered.

      We’re experts at making things easy with top-tier tech support and resources for any SOS moments. Plus, we’re your biggest fans. Go you! Our Shared Hosting plans + your epic blogging skills = the perfect pair.



      Source link

      How To Write Asynchronous Code in Node.js


      The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      For many programs in JavaScript, code is executed as the developer writes it—line by line. This is called synchronous execution, because the lines are executed one after the other, in the order they were written. However, not every instruction you give to the computer needs to be attended to immediately. For example, if you send a network request, the process executing your code will have to wait for the data to return before it can work on it. In this case, time would be wasted if it did not execute other code while waiting for the network request to be completed. To solve this problem, developers use asynchronous programming, in which lines of code are executed in a different order than the one in which they were written. With asynchronous programming, we can execute other code while we wait for long activities like network requests to finish.

      JavaScript code is executed on a single thread within a computer process. Its code is processed synchronously on this thread, with only one instruction run at a time. Therefore, if we were to do a long-running task on this thread, all of the remaining code is blocked until the task is complete. By leveraging JavaScript’s asynchronous programming features, we can offload long-running tasks to a background thread to avoid this problem. When the task is complete, the code we need to process the task’s data is put back on the main single thread.

      In this tutorial, you will learn how JavaScript manages asynchronous tasks with help from the Event Loop, which is a JavaScript construct that completes a new task while waiting for another. You will then create a program that uses asynchronous programming to request a list of movies from a Studio Ghibli API and save the data to a CSV file. The asynchronous code will be written in three ways: callbacks, promises, and with the async/await keywords.

      Note: As of this writing, asynchronous programming is no longer done using only callbacks, but learning this obsolete method can provide great context as to why the JavaScript community now uses promises. The async/await keywords enable us to use promises in a less verbose way, and are thus the standard way to do asynchronous programming in JavaScript at the time of writing this article.

      Prerequisites

      The Event Loop

      Let’s begin by studying the internal workings of JavaScript function execution. Understanding how this behaves will allow you to write asynchronous code more deliberately, and will help you with troubleshooting code in the future.

      As the JavaScript interpreter executes the code, every function that is called is added to JavaScript’s call stack. The call stack is a stack—a list-like data structure where items can only be added to the top, and removed from the top. Stacks follow the “Last in, first out” or LIFO principle. If you add two items on the stack, the most recently added item is removed first.

      Let’s illustrate with an example using the call stack. If JavaScript encounters a function functionA() being called, it is added to the call stack. If that function functionA() calls another function functionB(), then functionB() is added to the top of the call stack. As JavaScript completes the execution of a function, it is removed from the call stack. Therefore, JavaScript will execute functionB() first, remove it from the stack when complete, and then finish the execution of functionA() and remove it from the call stack. This is why inner functions are always executed before their outer functions.

      When JavaScript encounters an asynchronous operation, like writing to a file, it adds it to a table in its memory. This table stores the operation, the condition for it to be completed, and the function to be called when it’s completed. As the operation completes, JavaScript adds the associated function to the message queue. A queue is another list-like data structure where items can only be added to the bottom but removed from the top. In the message queue, if two or more asynchronous operations are ready for their functions to be executed, the asynchronous operation that was completed first will have its function marked for execution first.

      Functions in the message queue are waiting to be added to the call stack. The event loop is a perpetual process that checks if the call stack is empty. If it is, then the first item in the message queue is moved to the call stack. JavaScript prioritizes functions in the message queue over function calls it interprets in the code. The combined effect of the call stack, message queue, and event loop allows JavaScript code to be processed while managing asynchronous activities.

      Now that you have a high-level understanding of the event loop, you know how the asynchronous code you write will be executed. With this knowledge, you can now create asynchronous code with three different approaches: callbacks, promises, and async/await.

      Asynchronous Programming with Callbacks

      A callback function is one that is passed as an argument to another function, and then executed when the other function is finished. We use callbacks to ensure that code is executed only after an asynchronous operation is completed.

      For a long time, callbacks were the most common mechanism for writing asynchronous code, but now they have largely become obsolete because they can make code confusing to read. In this step, you’ll write an example of asynchronous code using callbacks so that you can use it as a baseline to see the increased efficiency of other strategies.

      There are many ways to use callback functions in another function. Generally, they take this structure:

      function asynchronousFunction([ Function Arguments ], [ Callback Function ]) {
          [ Action ]
      }
      

      While it is not syntactically required by JavaScript or Node.js to have the callback function as the last argument of the outer function, it is a common practice that makes callbacks easier to identify. It’s also common for JavaScript developers to use an anonymous function as a callback. Anonymous functions are those created without a name. It’s usually much more readable when a function is defined at the end of the argument list.

      To demonstrate callbacks, let’s create a Node.js module that writes a list of Studio Ghibli movies to a file. First, create a folder that will store our JavaScript file and its output:

      Then enter that folder:

      We will start by making an HTTP request to the Studio Ghibli API, which our callback function will log the results of. To do this, we will install a library that allows us to access the data of an HTTP response in a callback.

      In your terminal, initialize npm so we can have a reference for our packages later:

      Then, install the request library:

      Now open a new file called callbackMovies.js in a text editor like nano:

      In your text editor, enter the following code. Let’s begin by sending an HTTP request with the request module:

      callbackMovies.js

      const request = require('request');
      
      request('https://ghibliapi.herokuapp.com/films');
      

      In the first line, we load the request module that was installed via npm. The module returns a function that can make HTTP requests; we then save that function in the request constant.

      We then make the HTTP request using the request() function. Let’s now print the data from the HTTP request to the console by adding the highlighted changes:

      callbackMovies.js

      const request = require('request');
      
      request('https://ghibliapi.herokuapp.com/films', (error, response, body) => {
          if (error) {
              console.error(`Could not send request to API: ${error.message}`);
              return;
          }
      
          if (response.statusCode != 200) {
              console.error(`Expected status code 200 but received ${response.statusCode}.`);
              return;
          }
      
          console.log('Processing our list of movies');
          movies = JSON.parse(body);
          movies.forEach(movie => {
              console.log(`${movie['title']}, ${movie['release_date']}`);
          });
      });
      

      When we use the request() function, we give it two parameters:

      • The URL of the website we are trying to request
      • A callback function that handles any errors or successful responses after the request is complete

      Our callback function has three arguments: error, response, and body. When the HTTP request is complete, the arguments are automatically given values depending on the outcome. If the request failed to send, then error would contain an object, but response and body would be null. If it made the request successfully, then the HTTP response is stored in response. If our HTTP response returns data (in this example we get JSON) then the data is set in body.

      Our callback function first checks to see if we received an error. It’s best practice to check for errors in a callback first so the execution of the callback won’t continue with missing data. In this case, we log the error and the function’s execution. We then check the status code of the response. Our server may not always be available, and APIs can change causing once sensible requests to become incorrect. By checking that the status code is 200, which means the request was “OK”, we can have confidence that our response is what we expect it to be.

      Finally, we parse the response body to an Array and loop through each movie to log its name and release year.

      After saving and quitting the file, run this script with:

      You will get the following output:

      Output

      Castle in the Sky, 1986 Grave of the Fireflies, 1988 My Neighbor Totoro, 1988 Kiki's Delivery Service, 1989 Only Yesterday, 1991 Porco Rosso, 1992 Pom Poko, 1994 Whisper of the Heart, 1995 Princess Mononoke, 1997 My Neighbors the Yamadas, 1999 Spirited Away, 2001 The Cat Returns, 2002 Howl's Moving Castle, 2004 Tales from Earthsea, 2006 Ponyo, 2008 Arrietty, 2010 From Up on Poppy Hill, 2011 The Wind Rises, 2013 The Tale of the Princess Kaguya, 2013 When Marnie Was There, 2014

      We successfully received a list of Studio Ghibli movies with the year they were released. Now let’s complete this program by writing the movie list we are currently logging into a file.

      Update the callbackMovies.js file in your text editor to include the following highlighted code, which creates a CSV file with our movie data:

      callbackMovies.js

      const request = require('request');
      const fs = require('fs');
      
      request('https://ghibliapi.herokuapp.com/films', (error, response, body) => {
          if (error) {
              console.error(`Could not send request to API: ${error.message}`);
              return;
          }
      
          if (response.statusCode != 200) {
              console.error(`Expected status code 200 but received ${response.statusCode}.`);
              return;
          }
      
          console.log('Processing our list of movies');
          movies = JSON.parse(body);
          let movieList = '';
          movies.forEach(movie => {
              movieList += `${movie['title']}, ${movie['release_date']}n`;
          });
      
          fs.writeFile('callbackMovies.csv', movieList, (error) => {
              if (error) {
                  console.error(`Could not save the Ghibli movies to a file: ${error}`);
                  return;
              }
      
              console.log('Saved our list of movies to callbackMovies.csv');;
          });
      });
      

      Noting the highlighted changes, we see that we import the fs module. This module is standard in all Node.js installations, and it contains a writeFile() method that can asynchronously write to a file.

      Instead of logging the data to the console, we now add it to a string variable movieList. We then use writeFile() to save the contents of movieList to a new file—callbackMovies.csv. Finally, we provide a callback to the writeFile() function, which has one argument: error. This allows us to handle cases where we are not able to write to a file, for example when the user we are running the node process on does not have those permissions.

      Save the file and run this Node.js program once again with:

      In your ghibliMovies folder, you will see callbackMovies.csv, which has the following content:

      callbackMovies.csv

      Castle in the Sky, 1986
      Grave of the Fireflies, 1988
      My Neighbor Totoro, 1988
      Kiki's Delivery Service, 1989
      Only Yesterday, 1991
      Porco Rosso, 1992
      Pom Poko, 1994
      Whisper of the Heart, 1995
      Princess Mononoke, 1997
      My Neighbors the Yamadas, 1999
      Spirited Away, 2001
      The Cat Returns, 2002
      Howl's Moving Castle, 2004
      Tales from Earthsea, 2006
      Ponyo, 2008
      Arrietty, 2010
      From Up on Poppy Hill, 2011
      The Wind Rises, 2013
      The Tale of the Princess Kaguya, 2013
      When Marnie Was There, 2014
      

      It’s important to note that we write to our CSV file in the callback of the HTTP request. Once the code is in the callback function, it will only write to the file after the HTTP request was completed. If we wanted to communicate to a database after we wrote our CSV file, we would make another asynchronous function that would be called in the callback of writeFile(). The more asynchronous code we have, the more callback functions have to be nested.

      Let’s imagine that we want to execute five asynchronous operations, each one only able to run when another is complete. If we were to code this, we would have something like this:

      doSomething1(() => {
          doSomething2(() => {
              doSomething3(() => {
                  doSomething4(() => {
                      doSomething5(() => {
                          // final action
                      });
                  });
              }); 
          });
      });
      

      When nested callbacks have many lines of code to execute, they become substantially more complex and unreadable. As your JavaScript project grows in size and complexity, this effect will become more pronounced, until it is eventually unmanageable. Because of this, developers no longer use callbacks to handle asynchronous operations. To improve the syntax of our asynchronous code, we can use promises instead.

      Using Promises for Concise Asynchronous Programming

      A promise is a JavaScript object that will return a value at some point in the future. Asynchronous functions can return promise objects instead of concrete values. If we get a value in the future, we say that the promise was fulfilled. If we get an error in the future, we say that the promise was rejected. Otherwise, the promise is still being worked on in a pending state.

      Promises generally take the following form:

      promiseFunction()
          .then([ Callback Function for Fulfilled Promise ])
          .catch([ Callback Function for Rejected Promise ])
      

      As shown in this template, promises also use callback functions. We have a callback function for the then() method, which is executed when a promise is fulfilled. We also have a callback function for the catch() method to handle any errors that come up while the promise is being executed.

      Let’s get firsthand experience with promises by rewriting our Studio Ghibli program to use promises instead.

      Axios is a promise-based HTTP client for JavaScript, so let’s go ahead and install it:

      Now, with your text editor of choice, create a new file promiseMovies.js:

      Our program will make an HTTP request with axios and then use a special promised-based version of fs to save to a new CSV file.

      Type this code in promiseMovies.js so we can load Axios and send an HTTP request to the movie API:

      promiseMovies.js

      const axios = require('axios');
      
      axios.get('https://ghibliapi.herokuapp.com/films');
      

      In the first line we load the axios module, storing the returned function in a constant called axios. We then use the axios.get() method to send an HTTP request to the API.

      The axios.get() method returns a promise. Let’s chain that promise so we can print the list of Ghibli movies to the console:

      promiseMovies.js

      const axios = require('axios');
      const fs = require('fs').promises;
      
      
      axios.get('https://ghibliapi.herokuapp.com/films')
          .then((response) => {
              console.log('Successfully retrieved our list of movies');
              response.data.forEach(movie => {
                  console.log(`${movie['title']}, ${movie['release_date']}`);
              });
          })
      

      Let’s break down what’s happening. After making an HTTP GET request with axios.get(), we use the then() function, which is only executed when the promise is fulfilled. In this case, we print the movies to the screen like we did in the callbacks example.

      To improve this program, add the highlighted code to write the HTTP data to a file:

      promiseMovies.js

      const axios = require('axios');
      const fs = require('fs').promises;
      
      
      axios.get('https://ghibliapi.herokuapp.com/films')
          .then((response) => {
              console.log('Successfully retrieved our list of movies');
              let movieList = '';
              response.data.forEach(movie => {
                  movieList += `${movie['title']}, ${movie['release_date']}n`;
              });
      
              return fs.writeFile('promiseMovies.csv', movieList);
          })
          .then(() => {
              console.log('Saved our list of movies to promiseMovies.csv');
          })
      

      We additionally import the fs module once again. Note how after the fs import we have .promises. Node.js includes a promised-based version of the callback-based fs library, so backward compatibility is not broken in legacy projects.

      The first then() function that processes the HTTP request now calls fs.writeFile() instead of printing to the console. Since we imported the promise-based version of fs, our writeFile() function returns another promise. As such, we append another then() function for when the writeFile() promise is fulfilled.

      A promise can return a new promise, allowing us to execute promises one after the other. This paves the way for us to perform multiple asynchronous operations. This is called promise chaining, and it is analogous to nesting callbacks. The second then() is only called after we successfully write to the file.

      Note: In this example, we did not check for the HTTP status code like we did in the callback example. By default, axios does not fulfil its promise if it gets a status code indicating an error. As such, we no longer need to validate it.

      To complete this program, chain the promise with a catch() function as it is highlighted in the following:

      promiseMovies.js

      const axios = require('axios');
      const fs = require('fs').promises;
      
      
      axios.get('https://ghibliapi.herokuapp.com/films')
          .then((response) => {
              console.log('Successfully retrieved our list of movies');
              let movieList = '';
              response.data.forEach(movie => {
                  movieList += `${movie['title']}, ${movie['release_date']}n`;
              });
      
              return fs.writeFile('promiseMovies.csv', movieList);
          })
          .then(() => {
              console.log('Saved our list of movies to promiseMovies.csv');
          })
          .catch((error) => {
              console.error(`Could not save the Ghibli movies to a file: ${error}`);
          });
      

      If any promise is not fulfilled in the chain of promises, JavaScript automatically goes to the catch() function if it was defined. That’s why we only have one catch() clause even though we have two asynchronous operations.

      Let’s confirm that our program produces the same output by running:

      In your ghibliMovies folder, you will see the promiseMovies.csv file containing:

      promiseMovies.csv

      Castle in the Sky, 1986
      Grave of the Fireflies, 1988
      My Neighbor Totoro, 1988
      Kiki's Delivery Service, 1989
      Only Yesterday, 1991
      Porco Rosso, 1992
      Pom Poko, 1994
      Whisper of the Heart, 1995
      Princess Mononoke, 1997
      My Neighbors the Yamadas, 1999
      Spirited Away, 2001
      The Cat Returns, 2002
      Howl's Moving Castle, 2004
      Tales from Earthsea, 2006
      Ponyo, 2008
      Arrietty, 2010
      From Up on Poppy Hill, 2011
      The Wind Rises, 2013
      The Tale of the Princess Kaguya, 2013
      When Marnie Was There, 2014
      

      With promises, we can write much more concise code than using only callbacks. The promise chain of callbacks is a cleaner option than nesting callbacks. However, as we make more asynchronous calls, our promise chain becomes longer and harder to maintain.

      The verbosity of callbacks and promises come from the need to create functions when we have the result of an asynchronous task. A better experience would be to wait for an asynchronous result and put it in a variable outside the function. That way, we can use the results in the variables without having to make a function. We can achieve this with the async and await keywords.

      Writing JavaScript with async/await

      The async/await keywords provide an alternative syntax when working with promises. Instead of having the result of a promise available in the then() method, the result is returned as a value like in any other function. We define a function with the async keyword to tell JavaScript that it’s an asynchronous function that returns a promise. We use the await keyword to tell JavaScript to return the results of the promise instead of returning the promise itself when it’s fulfilled.

      In general, async/await usage looks like this:

      async function() {
          await [Asynchronous Action]
      }
      

      Let’s see how using async/await can improve our Studio Ghibli program. Use your text editor to create and open a new file asyncAwaitMovies.js:

      In your newly opened JavaScript file, let’s start by importing the same modules we used in our promise example:

      asyncAwaitMovies.js

      const axios = require('axios');
      const fs = require('fs').promises;
      

      The imports are the same as promiseMovies.js because async/await uses promises.

      Now we use the async keyword to create a function with our asynchronous code:

      asyncAwaitMovies.js

      const axios = require('axios');
      const fs = require('fs').promises;
      
      async function saveMovies() {}
      

      We create a new function called saveMovies() but we include async at the beginning of its definition. This is important as we can only use the await keyword in an asynchronous function.

      Use the await keyword to make an HTTP request that gets the list of movies from the Ghibli API:

      asyncAwaitMovies.js

      const axios = require('axios');
      const fs = require('fs').promises;
      
      async function saveMovies() {
          let response = await axios.get('https://ghibliapi.herokuapp.com/films');
          let movieList = '';
          response.data.forEach(movie => {
              movieList += `${movie['title']}, ${movie['release_date']}n`;
          });
      }
      

      In our saveMovies() function, we make an HTTP request with axios.get() like before. This time, we don’t chain it with a then() function. Instead, we add await before it is called. When JavaScript sees await, it will only execute the remaining code of the function after axios.get() finishes execution and sets the response variable. The other code saves the movie data so we can write to a file.

      Let’s write the movie data to a file:

      asyncAwaitMovies.js

      const axios = require('axios');
      const fs = require('fs').promises;
      
      async function saveMovies() {
          let response = await axios.get('https://ghibliapi.herokuapp.com/films');
          let movieList = '';
          response.data.forEach(movie => {
              movieList += `${movie['title']}, ${movie['release_date']}n`;
          });
          await fs.writeFile('asyncAwaitMovies.csv', movieList);
      }
      

      We also use the await keyword when we write to the file with fs.writeFile().

      To complete this function, we need to catch errors our promises can throw. Let’s do this by encapsulating our code in a try/catch block:

      asyncAwaitMovies.js

      const axios = require('axios');
      const fs = require('fs').promises;
      
      async function saveMovies() {
          try {
              let response = await axios.get('https://ghibliapi.herokuapp.com/films');
              let movieList = '';
              response.data.forEach(movie => {
                  movieList += `${movie['title']}, ${movie['release_date']}n`;
              });
              await fs.writeFile('asyncAwaitMovies.csv', movieList);
          } catch (error) {
              console.error(`Could not save the Ghibli movies to a file: ${error}`);
          }
      }
      
      

      Since promises can fail, we encase our asynchronous code with a try/catch clause. This will capture any errors that are thrown when either the HTTP request or file writing operations fail.

      Finally, let’s call our asynchronous function saveMovies() so it will be executed when we run the program with node

      asyncAwaitMovies.js

      const axios = require('axios');
      const fs = require('fs').promises;
      
      async function saveMovies() {
          try {
              let response = await axios.get('https://ghibliapi.herokuapp.com/films');
              let movieList = '';
              response.data.forEach(movie => {
                  movieList += `${movie['title']}, ${movie['release_date']}n`;
              });
              await fs.writeFile('asyncAwaitMovies.csv', movieList);
          } catch (error) {
              console.error(`Could not save the Ghibli movies to a file: ${error}`);
          }
      }
      
      saveMovies();
      

      At a glance, this looks like a typical synchronous JavaScript code block. It has fewer functions being passed around, which looks a bit neater. These small tweaks make asynchronous code with async/await easier to maintain.

      Test this iteration of our program by entering this in your terminal:

      In your ghibliMovies folder, a new asyncAwaitMovies.csv file will be created with the following contents:

      asyncAwaitMovies.csv

      Castle in the Sky, 1986
      Grave of the Fireflies, 1988
      My Neighbor Totoro, 1988
      Kiki's Delivery Service, 1989
      Only Yesterday, 1991
      Porco Rosso, 1992
      Pom Poko, 1994
      Whisper of the Heart, 1995
      Princess Mononoke, 1997
      My Neighbors the Yamadas, 1999
      Spirited Away, 2001
      The Cat Returns, 2002
      Howl's Moving Castle, 2004
      Tales from Earthsea, 2006
      Ponyo, 2008
      Arrietty, 2010
      From Up on Poppy Hill, 2011
      The Wind Rises, 2013
      The Tale of the Princess Kaguya, 2013
      When Marnie Was There, 2014
      

      You have now used the JavaScript features async/await to manage asynchronous code.

      Conclusion

      In this tutorial, you learned how JavaScript handles executing functions and managing asynchronous operations with the event loop. You then wrote programs that created a CSV file after making an HTTP request for movie data using various asynchronous programming techniques. First, you used the obsolete callback-based approach. You then used promises, and finally async/await to make the promise syntax more succinct.

      With your understanding of asynchronous code with Node.js, you can now develop programs that benefit from asynchronous programming, like those that rely on API calls. Have a look at this list of public APIs. To use them, you will have to make asynchronous HTTP requests like we did in this tutorial. For further study, try building an app that uses these APIs to practice the techniques you learned here.



      Source link

      How To Write Switch Statements in Go


      Introduction

      Conditional statements give programmers the ability to direct their programs to take some action if a condition is true and another action if the condition is false. Frequently, we want to compare some variable against multiple possible values, taking different actions in each circumstance. It’s possible to make this work using if statements alone. Writing software, however, is not only about making things work but also communicating your intention to your future self and other developers. switch is an alternative conditional statement useful for communicating actions taken by your Go programs when presented with different options.

      Everything we can write with the switch statement can also be written with if statements. In this tutorial, we’ll look at a few examples of what the switch statement can do, the if statements it replaces, and where it’s most appropriately applied.

      Structure of Switch Statements

      Switch is commonly used to describe the actions taken by a program when a variable is assigned specific values. The following example demonstrates how we would accomplish this using if statements:

      package main
      
      import "fmt"
      
      func main() {
          flavors := []string{"chocolate", "vanilla", "strawberry", "banana"}
      
          for _, flav := range flavors {
              if flav == "strawberry" {
                  fmt.Println(flav, "is my favorite!")
                  continue
              }
      
              if flav == "vanilla" {
                  fmt.Println(flav, "is great!")
                  continue
              }
      
              if flav == "chocolate" {
                  fmt.Println(flav, "is great!")
                  continue
              }
      
              fmt.Println("I've never tried", flav, "before")
          }
      }
      

      This will generate the following output:

      Output

      chocolate is great! vanilla is great! strawberry is my favorite! I've never tried banana before

      Within main, we define a slice of ice-cream flavors. We then use a for loop to iterate through them. We use three if statements to print out different messages indicating preferences for different ice-cream flavors. Each if statement must use the continue statement to stop execution of the for loop so that the default message at the end is not printed for the preferred ice-cream flavors.

      As we add new ice-cream preferences, we have to keep adding if statements to handle the new cases. Duplicated messages, as in the case of "vanilla" and "chocolate", must have duplicated if statements. To future readers of our code (ourselves included), the repetitive nature of the if statements obscures the important part of what they are doing—comparing the variable against multiple values and taking different actions. Also, our fallback message is set apart from the conditionals, making it appear unrelated. The switch statement can help us organize this logic better.

      The switch statement begins with the switch keyword and is followed, in its most basic form, with some variable to perform comparisons against. This is followed by a pair of curly braces ({}) where multiple case clauses can appear. Case clauses describe the actions your Go program should take when the variable provided to the switch statement equals the value referenced by the case clause. The following example converts the previous example to use a switch instead of multiple if statements:

      package main
      
      import "fmt"
      
      func main() {
          flavors := []string{"chocolate", "vanilla", "strawberry", "banana"}
      
          for _, flav := range flavors {
              switch flav {
              case "strawberry":
                  fmt.Println(flav, "is my favorite!")
              case "vanilla", "chocolate":
                  fmt.Println(flav, "is great!")
              default:
                  fmt.Println("I've never tried", flav, "before")
              }
          }
      }
      

      The output is the same as before:

      Output

      chocolate is great! vanilla is great! strawberry is my favorite! I've never tried banana before

      We’ve once again defined a slice of ice-cream flavors in main and used the range statement to iterate over each flavor. This time, however, we’ve used a switch statement that will examine the flav variable. We use two case clauses to indicate preferences. We no longer need continue statements as only one case clause will be executed by the switch statement. We’re also able to combine the duplicated logic of the "chocolate" and "vanilla" conditionals by separating each with a comma in the declaration of the case clause. The default clause serves as our catch-all clause. It will run for any flavors that we haven’t accounted for in the body of the switch statement. In this case, "banana" will cause default to execute, printing the message I've never tried banana before.

      This simplified form of switch statements addresses the most common use for them: comparing a variable against multiple alternatives. It also provides conveniences for us where we want to take the same action for multiple different values and some other action when none of the listed conditions are met by using the provided default keyword.

      When this simplified form of switch proves too limiting, we can use a more general form of switch statement.

      General Switch Statements

      switch statements are useful for grouping collections of more complicated conditionals to show that they are somehow related. This is most commonly used when comparing some variable against a range of values, rather than specific values as in the earlier example. The following example implements a guessing game using if statements that could benefit from a switch statement:

      package main
      
      import (
          "fmt"
          "math/rand"
          "time"
      )
      
      func main() {
          rand.Seed(time.Now().UnixNano())
          target := rand.Intn(100)
      
          for {
              var guess int
              fmt.Print("Enter a guess: ")
              _, err := fmt.Scanf("%d", &guess)
              if err != nil {
                  fmt.Println("Invalid guess: err:", err)
                  continue
              }
      
              if guess > target {
                  fmt.Println("Too high!")
                  continue
              }
      
              if guess < target {
                  fmt.Println("Too low!")
                  continue
              }
      
              fmt.Println("You win!")
              break
          }
      }
      

      The output will vary depending on the random number selected and how well you play the game. Here is the output from one example session:

      Output

      Enter a guess: 10 Too low! Enter a guess: 15 Too low! Enter a guess: 18 Too high! Enter a guess: 17 You win!

      Our guessing game needs a random number to compare guesses against, so we use the rand.Intn function from the math/rand package. To make sure we get different values for target each time we play the game, we use rand.Seed to randomize the random number generator based on the current time. The argument 100 to rand.Intn will give us a number in the range 0–100. We then use a for loop to begin collecting guesses from the player.

      The fmt.Scanf function gives us a means to read user input into a variable of our choosing. It takes a format string verb that converts the user’s input into the type we expect. %d here means we expect an int, and we pass the address of the guess variable so that fmt.Scanf is able to set that variable. After handling any parsing errors we then use two if statements to compare the user’s guess to the target value. The string that they return, along with bool, controls the message displayed to the player and whether the game will exit.

      These if statements obscure the fact that the range of values that the variable is being compared against are all related in some way. It can also be difficult, at a glance, to tell if we missed some part of the range. The next example refactors the previous example to use a switch statement instead:

      package main
      
      import (
          "fmt"
          "math/rand"
      )
      
      func main() {
          target := rand.Intn(100)
      
          for {
              var guess int
              fmt.Print("Enter a guess: ")
              _, err := fmt.Scanf("%d", &guess)
              if err != nil {
                  fmt.Println("Invalid guess: err:", err)
                  continue
              }
      
              switch {
              case guess > target:
                  fmt.Println("Too high!")
              case guess < target:
                  fmt.Println("Too low!")
              default:
                  fmt.Println("You win!")
                  return
              }
          }
      }
      

      This will generate output similar to the following:

      Output

      Enter a guess: 25 Too low! Enter a guess: 28 Too high! Enter a guess: 27 You win!

      In this version of the guessing game, we’ve replaced the block of if statements with a switch statement. We omit the expression argument to switch because we are only interested in using switch to collect conditionals together. Each case clause contains a different expression comparing guess against target. Similar to the first time we replaced if statements with switch, we no longer need continue statements since only one case clause will be executed. Finally, the default clause handles the case where guess == target since we have covered all other possible values with the other two case clauses.

      In the examples that we’ve seen so far, exactly one case statement will be executed. Occasionally, you may wish to combine the behaviors of multiple case clauses. switch statements provide another keyword for achieving this behavior.

      Fallthrough

      Sometimes you will want to reuse the code that another case clause contains. In these cases, it’s possible to ask Go to run the body of the next case clause listed using the fallthrough keyword. This next example modifies our earlier ice cream flavor example to more accurately reflect our enthusiasm for strawberry ice cream:

      package main
      
      import "fmt"
      
      func main() {
          flavors := []string{"chocolate", "vanilla", "strawberry", "banana"}
      
          for _, flav := range flavors {
              switch flav {
              case "strawberry":
                  fmt.Println(flav, "is my favorite!")
                  fallthrough
              case "vanilla", "chocolate":
                  fmt.Println(flav, "is great!")
              default:
                  fmt.Println("I've never tried", flav, "before")
              }
          }
      }
      

      We will see this output:

      Output

      chocolate is great! vanilla is great! strawberry is my favorite! strawberry is great! I've never tried banana before

      As we’ve seen previously, we define a slice of string to represent flavors and iterate through this using a for loop. The switch statement here is identical to the one we’ve seen before, but with the addition of the fallthrough keyword at the end of the case clause for "strawberry". This will cause Go to run the body of case "strawberry":, first printing out the string strawberry is my favorite!. When it encounters fallthrough it will run the body of the next case clause. This will cause the body of case "vanilla", "chocolate": to run, printing strawberry is great!.

      The fallthrough keyword is not used often by Go developers. Usually, the code reuse realized by using fallthrough can be better obtained by defining a function with the common code. For these reasons, using fallthrough is generally discouraged.

      Conclusion

      switch statements help us convey to other developers reading our code that a set of comparisons are somehow related to each other. They make it much easier to add different behavior when a new case is added in the future and make it possible to ensure that anything we forgot is handled properly as well with default clauses. The next time you find yourself writing multiple if statements that all involve the same variable, try rewriting it with a switch statement—you’ll find it easier to rework when it comes time to consider some other alternative value.

      If you’d like to learn more about the Go programming language, check out the entire How To Code in Go series.



      Source link