화살표 함수와 async/await를 사용하여 비동기 처리를 작성하는 방법을 구성해 보겠습니다.

소개.



오늘날의 최신 브라우저와 스마트폰에서는 Async/Await를 사용하는 Arrow 함수와 Promise의 사용을 Babel로 트랜스파일할 필요가 없습니다.

이러한 JavaScript 함수를 개별적으로 사용하는 방법을 살펴보면 오래된 방식으로 작성하는 방법을 많이 발견하고 현대적인 방식으로 작성하는 방법에 대해 혼란스러워할 것입니다.
  • 화살표 함수에서 함수를 정의하고 async/await를 사용하는 방법
    async/await가 중첩 방식으로 호출되면 어떻게 됩니까?
  • 비동기적으로 실행하고 결과를 기다리는 여러 작업을 실행하는 방법

  • 다음 표는 요약

    각 기능에 대한 브라우저 지원
  • arrow-functions
  • async
  • await

  • 아래 데모 링크에서 동작을 확인할 수 있습니다. 값을 변경하면서 동작을 확인하면 어떻게 동작하는지 이해하기 쉽습니다.
    DEMO

    화살표 함수를 사용하여 비동기/대기를 작성하는 방법


    몇 100ms를 잠자는 방법의 예



    Fetch 메서드와 같이 비동기적으로 데이터를 검색하는 예제의 더미로 사용할 수 있습니다.

    // 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}`
    }
    

    메서드 헤드에 async를 묶습니다const asyncFunc = async (mes) => {.

    비동기식으로 실행될 메서드의 완료를 기다릴 때 await를 비동기식 메서드await sleep(waitTime)에 연결합니다.

    이런 식으로 정의하면 asyncFunc 자체에서 result_${mes}를 가져올 때까지 기다려야 합니다. 이것은 아주 쉬운 일이 아닙니다.
    반환 값은 문자열이 아니라 Promise 개체입니다. 이것은 이미 JS를 복잡하게 만듭니다.

    반환 결과를 얻으려면 호출자에서 메서드에 await asyncFunc("message")await 접두사를 붙여야 합니다.

    async/await가 중첩이라고 하면 어떻게 되나요?



    Awai를 실행하려면 다음 예제와 같이 async를 사용하여 parentFunc를 생성하고 해당 함수에서 실행해야 합니다.
    이 함수에서 기본, 기본 2, 기본 3의 동작을 확인하고 무엇이 돌아오는지 확인하세요.
    이 함수의 마지막 줄이 이전 명령의 모든 결과를 완료하는지 확인하려면 Basic 3과 같이 작성할 수 있습니다.

    간단히 말해서, async에 정의된 함수 앞에 "await"를 쓰기만 하면 됩니다.

    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
    

    이름 없는 함수에서 async로 정의된 함수 실행



    "parentFunc"를 정의하지 않고도 실행할 수 있지만, 괄호를 많이 작성해야 해서 이해하기 어렵고 작성 방법이 직관적이지 않습니다.
    하지만 이해하기 쉽지 않은 괄호를 많이 써야 하고 쓰는 방법이 직관적이지 않습니다. 나는 이런 종류의 것을 아주 좋아한다고 말하지 않을 것입니다.

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



    비동기적으로 실행되고 결과를 기다리는 여러 작업을 어떻게 실행합니까?



    불행히도 async/await 코드에 숨긴 Promise를 작성해야 합니다.
    키워드는 Promise.all 입니다.Promise.all , 모든 스레드가 완료될 때까지 기다리는 프로세스와 유사합니다.

    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()
    

    좋은 웹페이지 즐겨찾기