Let's organize how to write asynchronous processing using arrow functions and async/await
Tags: javascript, async, await, arrowfunction
Published: 2020-09-06 05:45:15

# Introduction.
In today's modern browsers and smartphones, the use of Arrow functions and Promise using Async/Await doesn't need to be transpiled in Babel.

If you look into how to use these JavaScript functions individually, you'll find a lot of old ways of writing them, and you'll be confused as to how to write them in a modern way.

1. how to define a function in an arrow function and use async/await in it
What happens when async/await is called in a nested manner?
1. how to execute multiple things that run asynchronously and wait for the results

The following table summarizes the

Browser support for each function

* [arrow-functions](https://caniuse.com/#feat=arrow-functions)
* [async](https://caniuse.com/#search=async)
* [await](https://caniuse.com/#search=await)

You can check the behavior from the demo link below. It's easier to understand how it works if you check the action while changing the value.
[DEMO](https://playcode.io/656439/)



# How to write async/await using arrow functions

## Example of a method that sleeps a few 100ms

You can use it as a dummy for an example to retrieve data asynchronously, like the Fetch method.

```js
// sleep method Promise function that returns a time-consuming result such as fetch.
const sleep = (m) => new Promise( _ => setTimeout(_, m))

// Promise to use async-await to output a character after the Promise ends.
// Wait a few hundred ms at random.
const asyncFunc = async (mes) => {
    const waitTime = Math.floor((Math.random() * 100) + 1)
    await sleep(waitTime)
    console.log(mes)
    return `result_${mes}`
}
```

Enclose async at the head of the method, `const asyncFunc = async (mes) => {` 

Attach an await to the asynchronous method `await sleep(waitTime) ` when waiting for the completion of the method to be executed asynchronously.

If you define it in this way, you need to await to get the `result_${mes}` from asyncFunc itself. This isn't very easy.
The return value is not a string but a Promise object. This complicates JS already.

To get the result of the return, you need to prefix the method with `await asyncFunc("message") ` and `await` in the caller.

# what happens when async/await is called nested

To execute Awai, as shown in the following example, we need to create parentFunc using async and execute it in that function.
Please check the actions of basic, basic 2, and basic 3 in this function and see what comes back.
If you want to make sure that the last line of this function completes all the results of the previous commands, you can write it as in Basic 3.

In short, all you have to do is to write "await" before the function defined in async.

```js
const parentFunc = async () => {
  // The method using async will return a promise, so if you don't call it using async, you can't use awit and it will be asynchronous processing.
  const async = asyncFunc
  const sync = asyncFunc
  
  // The Basics
  console.log(async("async")) // The Promise object just returns
  console.log("---1---") // 1
  console.log(await sync("sync")) // 2

  // Basic 2
  console.log(await sync("sync2")) // 1
  console.log(async("async2")) // It just returns the Promise object
  console.log("---2---") // 2

  // Basic 3
  const resultSync = await sync("sync3") // 1
  console.log(await sync(resultSync)) // 2 Wait for the resultSync result and then run it
  console.log("---3---") // 3
}

parentFunc() //Execute the parentFunc defined above here
```

## Execute the function defined by async in an unnamed function

You can execute it without defining "parentFunc", but you need to write a lot of parentheses, which are difficult to understand, and the way to write it is not intuitive.
However, you need to write a lot of parentheses that are not easy to understand and the way to write it is not intuitive. I wouldn't say I like this kind of thing very much.

```js
(async () => {
  console.log(await asyncFunc("run a promise method that defines an anonymous function in async and executes it asynchronously"))
})()
```

-----

# How do I run multiple things that run asynchronously and wait for the results?
Unfortunately, we need to write the Promise that we hid in the async/await code.
The keyword is `Promise.all`.
`Promise.all`, which is similar to the process of waiting for all threads to complete.

```js
const parentFunc = async () => {
  // The method using async will return a promise, so if you don't call it using async, you can't use awit and it will be asynchronous processing.
  const async = asyncFunc
  const sync = asyncFunc
  
  // When asynchronous processing is entered in the map function
  // To take an array of id's and access the web API with each id as a parameter
  const arr = [1, 2, 3, 4, 5]

  // The order of the resultant array is the order of arr, even if the order in which each method in the map completes its execution is different.
  const result_arr1 = await Promise.all(arr.map((id)=>{
    return sync(id);
  })))
  console.log(result_arr1)
}

parentFunc()
```