One place for hosting & domains

      Exploring

      Exploring Async/Await Functions in JavaScript


      Introduction

      Promises give us an easier way to deal with asynchrony in our code in a sequential manner. Considering that our brains are not designed to deal with asynchronicity efficiently, this is a much welcome addition. Async/await functions, a new addition with ES2017 (ES8), help us even more in allowing us to write completely synchronous-looking code while performing asynchronous tasks behind the scenes.

      The functionality achieved using async functions can be recreated by combining promises with generators, but async functions give us what we need without any extra boilerplate code.

      Simple Example

      In the following example, we first declare a function that returns a promise that resolves to a value of 🤡 after 2 seconds. We then declare an async function and await for the promise to resolve before logging the message to the console:

      function scaryClown() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('🤡');
          }, 2000);
        });
      }
      
      async function msg() {
        const msg = await scaryClown();
        console.log('Message:', msg);
      }
      
      msg(); // Message: 🤡 <-- after 2 seconds
      

      await is a new operator used to wait for a promise to resolve or reject. It can only be used inside an async function.

      The power of async functions becomes more evident when there are multiple steps involved:

      function who() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('🤡');
          }, 200);
        });
      }
      
      function what() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('lurks');
          }, 300);
        });
      }
      
      function where() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('in the shadows');
          }, 500);
        });
      }
      
      async function msg() {
        const a = await who();
        const b = await what();
        const c = await where();
      
        console.log(`${ a } ${ b } ${ c }`);
      }
      
      msg(); // 🤡 lurks in the shadows <-- after 1 second
      

      A word of caution however, in the above example each step is done sequentially, with each additional step waiting for the step before to resolve or reject before continuing. If you instead want the steps to happen in parallel, you can simply use Promise.all to wait for all the promises to have fulfilled:

      // ...
      
      async function msg() {
        const [a, b, c] = await Promise.all([who(), what(), where()]);
      
        console.log(`${ a } ${ b } ${ c }`);
      }
      
      msg(); // 🤡 lurks in the shadows <-- after 500ms
      

      Promise.all returns an array with the resolved values once all the passed-in promises have resolved.

      In the above we also make use of some nice array destructuring to make our code succinct.

      Promise-Returning

      Async functions always return a promise, so the following may not produce the result you’re after:

      async function hello() {
        return 'Hello Alligator!';
      }
      
      const b = hello();
      
      console.log(b); // [object Promise] { ... }
      

      Since what’s returned is a promise, you could do something like this instead:

      async function hello() {
        return 'Hello Alligator!';
      }
      
      const b = hello();
      
      b.then(x => console.log(x)); // Hello Alligator!
      

      …or just this:

      async function hello() {
        return 'Hello Alligator!';
      }
      
      hello().then(x => console.log(x)); // Hello Alligator!
      

      Different Forms

      So far with our examples we saw the async function as a function declaration, but you we can also define async function expressions and async arrow functions:

      Async Function Expression

      Here’s the async function from our first example, but defined as a function expression:

      const msg = async function() {
        const msg = await scaryClown();
        console.log('Message:', msg);
      }
      

      Async Arrow Function

      Here’s that same example once again, but this time defined as an arrow function:

      const msg = async () => {
        const msg = await scaryClown();
        console.log('Message:', msg);
      }
      

      Error Handling

      Something else that’s very nice about async functions is that error handling is also done completely synchronously, using good old try…catch statements. Let’s demonstrate by using a promise that will reject half the time:

      function yayOrNay() {
        return new Promise((resolve, reject) => {
          const val = Math.round(Math.random() * 1); // 0 or 1, at random
      
          val ? resolve('Lucky!!') : reject('Nope 😠');
        });
      }
      
      async function msg() {
        try {
          const msg = await yayOrNay();
          console.log(msg);
        } catch(err) {
          console.log(err);
        }
      }
      
      msg(); // Lucky!!
      msg(); // Lucky!!
      msg(); // Lucky!!
      msg(); // Nope 😠
      msg(); // Lucky!!
      msg(); // Nope 😠
      msg(); // Nope 😠
      msg(); // Nope 😠
      msg(); // Nope 😠
      msg(); // Lucky!!
      

      Given that async functions always return a promise, you can also deal with unhandled errors as you would normally using a catch statement:

      async function msg() {
        const msg = await yayOrNay();
        console.log(msg);
      }
      
      msg().catch(x => console.log(x));
      

      This synchronous error handling doesn’t just work when a promise is rejected, but also when there’s an actual runtime or syntax error happening. In the following example, the second time with call our msg function we pass in a number value that doesn’t have a toUpperCase method in its prototype chain. Our try…catch block catches that error just as well:

      function caserUpper(val) {
        return new Promise((resolve, reject) => {
          resolve(val.toUpperCase());
        });
      }
      
      async function msg(x) {
        try {
          const msg = await caserUpper(x);
          console.log(msg);
        } catch(err) {
          console.log('Ohh no:', err.message);
        }
      }
      
      msg('Hello'); // HELLO
      msg(34); // Ohh no: val.toUpperCase is not a function
      

      Async Functions With Promise-Based APIS

      As we showed in our primer to the Fetch API, web APIs that are promise-based are a perfect candidate for async functions:

      async function fetchUsers(endpoint) {
        const res = await fetch(endpoint);
        let data = await res.json();
      
        data = data.map(user => user.username);
      
        console.log(data);
      }
      
      fetchUsers('https://jsonplaceholder.typicode.com/users');
      // ["Bret", "Antonette", "Samantha", "Karianne", "Kamren", "Leopoldo_Corkery", "Elwyn.Skiles", "Maxime_Nienow", "Delphine", "Moriah.Stanton"]
      

      <%>[note]
      Browser Support:
      As of 2020, 94% of browsers worldwide can handle async/await in javascript Notable exceptions are IE11 and Opera Mini.

      Conclusion

      Before Async/await functions, JavaScript code that relied on lots of asynchronous events (for example: code that made lots of calls to APIs) would end up in what some called “callback hell” – A chain of functions and callbacks that was very difficult to read and understand.

      Async and await allow us to write asynchronous JavaScript code that reads much more clearly.



      Source link

      Exploring Multi-Column Layouts in CSS


      While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or
      edited it to ensure you have an error-free learning experience. It’s on our list, and we’re working on it!
      You can help us out by using the “report an issue” button at the bottom of the tutorial.

      Introduction

      Layouts where content flows between multiple columns and multi-column magazine-style layouts can now easily be implemented in CSS using a few simple rules defined as part of the CSS Multi-column Layout specification. This, along with CSS grid and flexbox, really allows us to define pretty much any kind of layout with minimum effort. Let’s go over what’s currently possible in terms of multi-column layouts.

      Basic Multi-Column Layouts

      Multi-column layouts are defined with either the column-count or the column-width properties set on a containing block element.

      column-count

      column-count takes an integer value for the number of columns that the block element should have:

      .col {
        background: var(--subtle-yellow2);
        padding: 1rem 2rem;
      }
      
      .col-3 {
        column-count: 3;
      }
      
      <article class="col col-3">
        <p>...</p>
        <p>...</p>
        <p>...</p>
      </article>
      

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.

      To create a responsive layout, it’s as simple as setting a different number of columns on smaller viewports:

      @media (max-width: 600px) {
        .col-3 {
          column-count: 1;
        }
      }
      @media (min-width: 601px)  and (max-width: 900px) {
        .col-3 {
          column-count: 2;
        }
      }
      

      column-width

      With column-width, instead of providing an exact number of columns, you provide a suggested width for them and the number of columns will be computed against that and the available space. Here’s an example where columns have a width of 8rem:

      .col-8rem {
        column-width: 8rem;
      }
      
      <article class="col col-8rem">
        <p>...</p>
        <p>...</p>
        <p>...</p>
      </article>
      

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.

      If you resize your viewport you’ll notice that using column-width will make the multi-column layout responsive by default without the need to define a different number of columns for smaller viewports.

      columns

      There’s also a shorthand property for column-count and column-with called columns. Here’s how you would set a container to have 2 columns or columns with a width of 12rem:

      .col-2-12rem {
        columns: 2 12rem;
      }
      

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.

      Setting both a column count and a column width is perhaps a bit odd for most use cases, because it’s then left to the browser to decide to follow either the provided count or the width.

      Gaps & Rules

      You can specify the width of the gaps between columns using the column-gap property and you can define a rule (line) in the middle of the gap using the column-rule property.

      column-gap

      By default most browsers will use a column gap of 1rem if none is specified. Here’s an example with a 5rem column-gap:

      .col-gap-5rem {
        column-gap: 5rem;
      }
      
      <article class="col col-gap-5rem col-3">
        <p>...</p>
        <p>...</p>
        <p>...</p>
      </article>
      

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.

      column-rule

      A rule is just a line between two columns that have content. The value for the column-rule is in the same format as values for border properties:

      .col-fancy-rule {
        column-rule: 3px dotted hotpink;
      }
      
      <article class="col col-fancy-rule col-3 col-gap-5rem">
        <p>...</p>
        <p>...</p>
        <p>...</p>
      </article>
      

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.

      Column Span

      With the column-span property set to a value of all, you can have elements within a multi-column elements that span the full width and force a row break:

      .col h3 {
        column-span: all;
        border-bottom: 2px solid var(--subtle-green1);
      }
      
      <article class="col col-fancy-rule col-3 col-gap-5rem">
        <p>...</p>
      
        <h3>Fancy-enough Title</h3>
      
        <p>...</p>
      
        <p>...</p>
      </article>
      

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Fancy-enough Title

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.

      Firefox doesn’t support column-span at the time of this writing.

      Column Breaks

      You can control how an element should break between columns with the break-before, break-inside and break-after properties and with values of avoid or avoid-column. Here’s a simple example where paragraph elements won’t break into multiple columns:

      .breaks p {
        break-inside: avoid-column;
      }
      
      <article class="col col-3 breaks">
        <p>...</p>
      
        <h3>Fancy-enough Title</h3>
      
        <p>...</p>
        <p>...</p>
      </article>
      

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Fancy-enough Title

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.

      The same example without the break-inside rule would look like this, where paragraphs can flow to multiple columns:

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Fancy-enough Title

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.

      Column Fill

      column-fill controls how the content will be distributed between columns. The initial value, balance, indicates to the browser that the content should be distributed evenly between the columns.

      First, here’s an example where we set a hard-coded height on the multi-column container and where the content is distributed evenly because of the initial value of balance:

      <article class="col col-3 b30" style="height: 400px;">
        <p>...</p>
        <p>...</p>
        <p>...</p>
      </article>
      

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.

      Now here’s the same example, but with column-fill set to auto instead:

      <article class="col col-3" style="column-fill: auto; height: 500px;">
        <p>...</p>
        <p>...</p>
        <p>...</p>
      </article>
      

      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

      Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

      Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus.

      Conclusion

      Multicolumn properties are yet another modern CSS layout tool along with CSS grid and flexbox that give creators the ability to quickly define flexible and dynamic layouts.

      Browser Support: As of 2020, Can I Use multicolumn? shows 99% of worldwide browsers support multicolumn properties discussed above. Browsers flagged as having partial support don’t support properties like column-context: avoid-column not discussed in this article.



      Source link

      Evolving Cyberattacks: Exploring the Changing Cybersecurity Landscape in 2020


      Cyberattacks have been plaguing the top headlines for years and security continues to be a top priority for enterprises across the globe. In fact, when IT pros were asked their top challenges for 2020, protecting their organizations from cyberattacks came in second only to migrating applications to the cloud.

      Many of these pros also noted that cybersecurity would have been a good area to focus on had they known when they entered the field how important security would become. And this is not without reason. Criminals perpetrating cyberattacks keep shifting their strategies to expose new vulnerabilities, and cybersecurity experts are essential to stop these attackers in their tracks.

      As the cybersecurity landscape continues to evolve, it’s crucial to maintain awareness and adjust security strategies accordingly. Let’s explore what’s changing and which attacks are on the rise.

      Targeted Ransomware Attacks

      Public reports from various vendors such as Check Point, Verisign and others all seem to agree that mass ransomware attacks peaked in 2017 and ran through 2018, with 30 percent of businesses and home users affected, according to Checkpoint’s 2020 Cyber Security Report. But a peak doesn’t mean that ransomware attacks are going away, rather, they shifted to more targeted ransomware attacks in 2019.

      Alert Logic notes in their Critical Watch Report that ransomware continues to be a popular cyberattack due to its profitability, simplicity (because it can be conducted from a computer anywhere in the world) and anonymity. Malicious attackers are always adapting to new environments and IT protection strategies. The larger numbers of attacks in 2017 were reported from organizations that received phishing emails containing ransomware software. This technique has a fairly low success rate. With the end goal of a company paying an attacker for encryption keys, there is also low probability that the majority of these organizations would even have the available funds to pay in the first place. A more targeted and sophisticated effort proves to have a much higher success rate.

      Rising Popularity of Cryptojacking

      With ransomware attacks on the decline, cryptojacking—a type of cyberattack in which a hacker secretly uses a target’s computer to mine for cryptocurrency—is seeing a massive rise in popularity. It’s less visible and doesn’t require the same effort as ransomware. One of the many examples of this trend is a cryptojacking attack on a cloud mining service, which took the scripting service offline for weeks and resulted in 65-million-dollars in stolen cryptocurrency. While the company was able to recover most of the currency, cryptojacking attacks continue to deliver potentially business-ending consequences to vulnerable organizations.

      Attackers are evolving to use many of the same exploit measures that spammers and DDoS attackers have been using for years. Gaining control of a machine through known vulnerabilities and using those compromised machines idles computing cycles to join a mining pool.

      There were 52.7 million cryptojacking hits in the first half of 2019. Cryptojacking is a growing threat as we progress into 2020, and we can expect that more and more idle compute resources will be compromised.

      Evolving DDoS Attacks

      DDoS attacks are still a rising method of cyberattack, and just like ransomware attacks morphing into cryptojacking, DDoS attacks are also evolving.

      Neustar’s Q2 and Q3 2019 reports suggest that the attack intensity, measured in Mpps (million packets per second), as well as attack size, measured in Gbps (gigabits per second), is dropping. The average intensity of attacks in 2018 measured at 4.5 Mpps, while the average was 1.3 Mpps. The largest DDoS attack, recorded in 2018, registered at 1.7 Tbps. The average attack size in 2019 was around 7.5 Gbps. This suggests that DDoS attacks are currently undergoing the same process of refinement as ransomware attacks.

      Increasingly sophisticated DDoS attacks are being used not to take a whole service offline with a volumetric attack, but to strategically target specific ports, gateways, services or applications. These attacks require much less traffic to take a service offline, and many times the attack is focused on network degradation as opposed to a downed site event.

      Other Types of Cyberattacks

      While some of these more popular attacks types peaked from 2017 and 2018, a few new forms of attacks are on the rise. Some are using classic tactics, with malicious attackers going back to more simplistic attack styles to exploit areas that may be lightly secured by more corporations. Attacks using web-form hijacking techniques are on the rise, and while it seems as though most companies have adequate controls, JavaScript-based attacks served 16 percent of all global attacks for the first half of 2019.

      JavaScript based attacks are reported only third to EXE and DOC based attacks. While many organizations have defense software or hardware to protect their services on an application level, there may still be gaps in security that allow for vulnerabilities. A failed policy to delete an administrator account after an employee departure, a patch that was never applied to an application or crucial upgrades to software that can’t be implemented due to how the application is developed all can result in an attack.

      Preventing Vulnerabilities

      In 2020, it’s more crucial than ever to update both business and technical security policies. Finding a partner you can trust is an important first step to effectively getting ahead of these evolving attacks, and to navigating and managing the complex tools that will keep your organization safe.

      At INAP, we offer managed security services for all cloud products that extend your team and safeguard critical infrastructure. Do your homework to ensure whichever partner you choose can adequately safeguard your infrastructure solutions, as well as adequately address the evolving cyberattack landscape.

      Explore INAP Managed Security.

      LEARN MORE

      Paul Just


      READ MORE



      Source link