Shubham Ankit

Shubham Ankit

1557203207

An introduction to JavaScript’s async and await

Asynchronous JavaScript has never been easy. For a while, we used callbacks. Then, we used promises. And now, we have asynchronous functions.

Asynchronous functions make it easier to write asynchronous JavaScript, but it comes with its own set of gotchas that makes life hard for beginners.

In this 2-part series, I want to share everything you need to know about asynchronous functions.

Asynchronous functions

Asynchronous functions contain the async keyword. You can use it in a normal function declaration:

async function functionName (arguments) {
 // Do something asynchronous
}

You can also use it in an arrow-function.

const functionName = async (arguments) => {
 // Do something asynchronous
}

Asynchronous functions always return promises

It doesn’t matter what you return. The returned value will always be a promise.

const getOne = async _ => { 
 return 1 
}

const promise = getOne()
console.log(promise) // Promise 

Note: You should know what are JavaScript Promises and how to use them before you move on. Otherwise, it’ll start to get confusing. Use this article to help you get familiar with JavaScript promises.

The await keyword

When you call a promise, you handle the next step in a then call, like this:

const getOne = async _ => { 
 return 1 
}

getOne()
 .then(value => {
 console.log(value) // 1
 })

The await keyword lets you wait for the promise to resolve. Once the promise is resolved, it returns the parameter passed into the then call.

const test = async _ => {
 const one = await getOne()
 console.log(one) // 1
}
test()

Return await

There’s no need to await before returning a promise. You can return the promise directly.

(If you return await something, you resolve the original promise first. Then, you create a new promise from the resolved value. return await effectively does nothing. No need for the extra step).

// Don’t need to do this 
const test = async _ => {
 return await getOne()
}
test()
 .then(value => {
 console.log(value) // 1
 })

// Do this instead
const test = async _ => {
 return getOne()
}
test()
 .then(value => {
 console.log(value) // 1
 })

Note: If you don’t need await, you don’t need to use an async function. The example above can be rewritten as follows:

// Do this instead
const test = _ => {
 return getOne()
}
test()
 .then(value => {
 console.log(value) // 1
 })

Handling errors

If a promise results in an error, you handle it with a catch call, like this:

const getOne = async (success = true) => { 
 if (success) return 1
 throw new Error(‘Failure!’)
}
getOne(false)
 .catch(error => console.log(error)) // Failure!

If you want to handle an error in an asynchronous function, you need to use a try/catch call.

const test = async _ => {
 try {
   const one = await getOne(false)
 } catch (error) {
   console.log(error) // Failure!
 }
}
test()

If you have multiple await keywords, error handling can become ugly…

const test = async _ => {
   try {
     const one = await getOne(false)
   } catch (error) {
     console.log(error) // Failure!
   }
  try {
    const two = await getTwo(false)
  } catch (error) {
    console.log(error) // Failure!
  }
  try {
    const three = await getThree(false)
  } catch (error) {
    console.log(error) // Failure!
  }
}
test()

There’s a better way.

We know that asynchronous functions always return a promise. When we call a promise, we can handle errors in a catch call. This means we can handle any errors from our asynchronous function by adding .catch.

const test = async _ => {
 const one = await getOne(false)
 const two = await getTwo(false)
 const three = await getThree(false)
}
test()
 .catch(error => console.log(error)))

Note: The Promise catch method lets you catch one error only.

Multiple awaits

await blocks JavaScript from executing the next line of code until a promise resolves. This may have the unintended consequence of slowing down code execution.

To show this in action, we need to create a delay before resolving the promise. We can create a delay with a sleep function.

const sleep = ms => {
 return new Promise(resolve => setTimeout(resolve, ms))
}

ms is the number of milliseconds to wait before resolving. If you pass in 1000 into sleep, JavaScript will wait for one second before resolving the promise.

// Using Sleep
console.log(‘Now’)
sleep(1000)
 .then(v => { console.log(‘After one second’) })

Image for post

Image for post

Console logs ‘now’ immediately. One second later, it logs ‘After one second’

Let’s say getOne takes one second to resolve. To create this delay, we pass 1000 (one second) into sleep. After one second has passed and the sleep promise resolves, we return the value 1.

const getOne = _ => {
 return sleep(1000).then(v => 1)
}

If you await getOne(), you’ll see that it takes one second before getOne resolves.

const test = async _ => {
 console.log(‘Now’)

 const one = await getOne()
 console.log(one)
}
test()

Image for post

Image for post

Console logs ‘Now’ immediately. After one second, console logs 1

Now let’s say you need to wait for three promises. Each promise has a one-second delay.

const getOne = _ => {
 return sleep(1000).then(v => 1)
}

const getTwo = _ => {
 return sleep(1000).then(v => 2)
}
const getThree = _ => {
 return sleep(1000).then(v => 3)
}

If you await these three promises in a row, you’ll have to wait for three seconds before all three promises get resolved. This is not good because we forced JavaScript to wait two extra seconds before doing what we need to do.

const test = async _ => {
 const one = await getOne()
 console.log(one)

 const two = await getTwo()
 console.log(two)
 const three = await getThree()
 console.log(three)
 console.log(‘Done’)
}
test()

Image for post

Image for post

Console shows ‘Now’ immediately. One second later, it shows 1. Another second later, it shows 2. Another second later, it shows 3 and ‘Done’ at the same time.

If getOnegetTwo and getThree can be fetched simultaneously, you’ll save two seconds. You can fetch these three promises at the same time with Promise.all.

There are three steps:

1. Create the three promises

2. Add all three promises into an array

3. await the array of promises with Promise.all

Here’s what it looks like:

const test = async _ => {
 const promises = [getOne(), getTwo(), getThree()]
 console.log(‘Now’)

 const [one, two, three] = await Promise.all(promises)
 console.log(one)
 console.log(two)
 console.log(three)
 console.log(‘Done’)
}
test()

Image for post

Image for post

Console shows ‘Now’ immediately. After one second, console shows 1, 2, 3, and ‘Done’

That’s all you need to know about basic asynchronous functions! I hope this article clears things up for you.

Note: This article is a modified excerpt from Learn JavaScript. If you find this article useful, you might want to check it out.

Next up, we’re going to look at asynchronous functions and its behavior in loops.

This article was originally posted on blog

#javascript

What is GEEK

Buddha Community

An introduction to JavaScript’s async and await
Mike  Kozey

Mike Kozey

1656151740

Test_cov_console: Flutter Console Coverage Test

Flutter Console Coverage Test

This small dart tools is used to generate Flutter Coverage Test report to console

How to install

Add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dev_dependencies:
  test_cov_console: ^0.2.2

How to run

run the following command to make sure all flutter library is up-to-date

flutter pub get
Running "flutter pub get" in coverage...                            0.5s

run the following command to generate lcov.info on coverage directory

flutter test --coverage
00:02 +1: All tests passed!

run the tool to generate report from lcov.info

flutter pub run test_cov_console
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
 print_cov_constants.dart                    |    0.00 |    0.00 |    0.00 |    no unit testing|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

Optional parameter

If not given a FILE, "coverage/lcov.info" will be used.
-f, --file=<FILE>                      The target lcov.info file to be reported
-e, --exclude=<STRING1,STRING2,...>    A list of contains string for files without unit testing
                                       to be excluded from report
-l, --line                             It will print Lines & Uncovered Lines only
                                       Branch & Functions coverage percentage will not be printed
-i, --ignore                           It will not print any file without unit testing
-m, --multi                            Report from multiple lcov.info files
-c, --csv                              Output to CSV file
-o, --output=<CSV-FILE>                Full path of output CSV file
                                       If not given, "coverage/test_cov_console.csv" will be used
-t, --total                            Print only the total coverage
                                       Note: it will ignore all other option (if any), except -m
-p, --pass=<MINIMUM>                   Print only the whether total coverage is passed MINIMUM value or not
                                       If the value >= MINIMUM, it will print PASSED, otherwise FAILED
                                       Note: it will ignore all other option (if any), except -m
-h, --help                             Show this help

example run the tool with parameters

flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

report for multiple lcov.info files (-m, --multi)

It support to run for multiple lcov.info files with the followings directory structures:
1. No root module
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
2. With root module
<root>/coverage/lcov.info
<root>/lib/src
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
You must run test_cov_console on <root> dir, and the report would be grouped by module, here is
the sample output for directory structure 'with root module':
flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock --multi
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_a -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_b -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

Output to CSV file (-c, --csv, -o, --output)

flutter pub run test_cov_console -c --output=coverage/test_coverage.csv

#### sample CSV output file:
File,% Branch,% Funcs,% Lines,Uncovered Line #s
lib/,,,,
test_cov_console.dart,0.00,0.00,0.00,no unit testing
lib/src/,,,,
parser.dart,100.00,100.00,97.22,"97"
parser_constants.dart,100.00,100.00,100.00,""
print_cov.dart,100.00,100.00,82.91,"29,49,51,52,171,174,177,180,183,184,185,186,187,188,279,324,325,387,388,389,390,391,392,393,394,395,398"
print_cov_constants.dart,0.00,0.00,0.00,no unit testing
All files with unit testing,100.00,100.00,86.07,""

Installing

Use this package as an executable

Install it

You can install the package from the command line:

dart pub global activate test_cov_console

Use it

The package has the following executables:

$ test_cov_console

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add test_cov_console

With Flutter:

 $ flutter pub add test_cov_console

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  test_cov_console: ^0.2.2

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:test_cov_console/test_cov_console.dart';

example/lib/main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Author: DigitalKatalis
Source Code: https://github.com/DigitalKatalis/test_cov_console 
License: BSD-3-Clause license

#flutter #dart #test 

Javascript : Async Await in Javascript | Javascript Interview questions.

Explained in detail about

  • Async
  • Await
  • Fetching country data using Async & Await
  • How Async & Await better than promise

Dont miss to watch the video & ask your questions or doubts in comments

https://youtu.be/pJbsd2vAqdI

#javascript #async #await

Introduction With Basic JavaScript

The world’s most misunderstood programming language is JavaScript but JavaScript is now used by an incredible number of high-profile applications. So, it’s an important skill for any web or mobile developer to enrich the deeper knowledge in it.

Unlike most programming languages, the JavaScript language has no concept of input or output. It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world.

Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with object prototypes, instead of classes. JavaScript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object.

Let’s start off by looking at the building blocks of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript’s types are:

· Number

· String

· Boolean

· Function

· Object

· Symbol

and undefined and null, which are … slightly odd. And Array, which is a special kind of object. Date and RegExp, which are objects that you get for free. And to be technically accurate, functions are just a special type of object. So the type of diagram looks like this:

#beginner-javascript #javascript #javascript-introduction #javascript-fundamental #basic-javascritp

Ollie  Dietrich

Ollie Dietrich

1636175760

How Async/Await Works in Javascript

Async/await is a new way to write asynchronous code.  Async/await is actually just syntax sugar built on top of promises. It makes asynchronous code look and behaves a little more like synchronous code.

 

Thumb Rules for async-await:
1. `async` functions return a promise.
2. `await` pauses the code execution within the `async` function.
3. There can be multiple `await` statements within a single `async` function.
4. `await` only pauses the code execution within the `async` function. It makes sure that the next line is executed when the promise resolves.

 

⌚ Timestamps:
00:00 Introduction
00:58 Async
02:27 Await

 #javascript  #async  #await 

Sadie  Cassin

Sadie Cassin

1598637660

How To Use Async/Await in JavaScript

How To Use Async/Await in JavaScript

SHARE     

Async/Await

The async and await is keywords to perform the promise-based asynchronous operation. In this article, we are going to learn how to use async/await in JavaScript.

How to use Async?

It is mandatory to define the async keyword before any function that turns your normal function to async function. Let’s start to learn it through a very basic example.

Normal Function Example

function sayHello() {
    return 'Hello World!';
}

sayHello(); // Hello World!

Copy

Async Function Example

async function sayHello() {
    return 'Hello World!';
}

sayHello(); // [object Promise] { ... }

Copy

We could explicitly return a promise with Promise.resolve() like:

async function sayHello() {
    return Promise.resolve('Hello World!');
}
async function sayHello() {
    return 'Hello World!';
}

let greeting = sayHello();
greeting.then((value) => console.log(value)); // Hello World!

Copy

or you can try this:

async function sayHello() {
    return 'Hello World!';
}

sayHello().then((value) => console.log(value) ); // Hello World!

#javascript #async #await