JavaScript의 Async/Await의 새로운 구문 이해

coldplay.xixi
풀어 주다: 2020-07-08 16:31:41
앞으로
2117명이 탐색했습니다.

JavaScript의 Async/Await의 새로운 구문 이해

Zeit 팀 블로그 게시물에서 영감을 받아 PayPal 팀은 최근 서버 측 데이터베이스를 Async/Await로 마이그레이션했습니다. 나는 내 경험을 당신과 공유하고 싶습니다.

먼저 두 가지 용어를 이해해 봅시다.

  • Async 함수
  • Await 키워드

항상 Async와 Await를 함께 이야기하지만, 알아야 할 것은 둘이 서로 다르다는 것입니다. Async 함수와 Await 키워드에 대해 이해해야 할 것은 분명히 어느 정도 관련이 있지만 Async 함수는 Await 없이도 사용할 수 있다는 것입니다.

관련 학습 권장사항: javascript 비디오 튜토리얼

함수는 Promise를 반환합니다.

async 키워드를 사용하여 함수를 생성하면 함수는 항상 Promise를 반환합니다. 비동기 함수 내부로 돌아오면 값을 Promise로 래핑합니다.

 // here is an async function
 async function getNumber() {

  return 4 // actually returns a Promise
  }
  // the same function using promises
  function getNumber() {

     return Promise.resolve(4)

}
로그인 후 복사

Async 함수와 Promise 기반 함수

return을 Promise로 변환하는 것 외에도 async 함수에는 특별한 점이 있습니다. 즉, wait 키워드를 사용할 수 있는 유일한 함수입니다. 장소.

Await를 사용하면 Promise의 결과를 받을 때까지 비동기 함수의 실행을 일시 중지할 수 있습니다. 이를 통해 실행 순서대로 나타나는 비동기 코드를 작성할 수 있습니다.

 // async function to show user data
 async function displayUserData() {

    let me = await fetch('/users/me')

    console.log(me)

}// promise-based equivalent
function displayUserData() {

    return fetch('/users/me').then(function(me) {

        console.log(me)

    })

})
로그인 후 복사

Await를 사용하면 콜백 없이도 비동기 코드를 작성할 수 있습니다. 이것의 장점은 코드를 더 쉽게 읽을 수 있다는 것입니다. 그리고 Wait는 비동기 함수로 생성된 Promise뿐만 아니라 모든 Promise와 호환됩니다.

비동기 함수의 오류 처리

비동기 함수도 Promise이기 때문에 코드에 비동기 함수를 넣으면 흡수된 후 거부된 Promise로 반환됩니다.

 // basic error handling with async functions
 async function getData(param) {

   if (isBad(param)) {     
    throw new Error("this is a bad param")

   }   
   // ...
   }
   // basic promise-based error handling example
   function getData(param) {

   if (isBad(param)) {      
   return Promise.reject(new Error("this is a bad param"))

   }  
    // ...
    }
로그인 후 복사

await를 사용하여 Promise를 호출할 때 try/catch로 래핑하거나 반환된 Promise에 catch 핸들러를 추가해야 합니다. try/catch将其包裹,或是你需要在返回的Promise中添加一个catch handler。

 // rely on try/catch around the awaited Promise

async function doSomething() {   
 try {       
  let data = await getData()

    } catch (err) {       
     console.error(err)

    }

}
// add a catch handlerfunction doSomething() {    
return getData().catch(err => {      
  console.error(err)

    })

}
로그인 후 복사

整合

利用好promise的错误处理属性,以及async函数的简洁语法,能够给你带来一些强大的能力。

在下面这个简单的例子中,你会看到我是如何利用async函数内在的错误处理能力的,它让我简化了Express应用中的错误处理流程。

 // catch any errors in the promise and either forward them to next(err) or ignore them
 const catchErrors = fn => (req, res, next) => fn(req, res, next).catch(next)
 const ignoreErrors = fn => (req, res, next) => fn(req, res, next).catch(() => next())
 // wrap my routes in those helpers functions to get error handling
 app.get('/sendMoney/:amount', catchErrors(sendMoney))
 // use our ignoreErrors helper to ignore any errors in the logging middleware
 app.get('/doSomethingElse', ignoreErrors(logSomething), doSomethingElse)
 // controller method can throw errors knowing router will pick it up
 export async function sendMoney(req, res, next) {  
 if (!req.param.amount) {     
 throw new Error('You need to provide an amount!')  

  }  await Money.sendPayment(amount) // no try/catch needed

  res.send(`You just sent ${amount}`)}

// basic async logging middleware
export async function logSomething(req, res, next) {

    // ...    
    throw new Error('Something went wrong with your logging')

    // ...

}
로그인 후 복사

此前,我们一直都在用next(err)来处理错误。然而,有了async/awaitrrreee

Integration🎜🎜🎜🎜Promise의 오류 처리 속성과 비동기 함수의 간결한 구문을 사용하면 몇 가지 강력한 기능을 얻을 수 있습니다. 🎜🎜아래의 간단한 예에서는 비동기 함수의 고유한 오류 처리 기능을 어떻게 활용하여 Express 애플리케이션의 오류 처리 프로세스를 단순화했는지 확인할 수 있습니다. 🎜rrreee🎜이전에는 next(err)를 사용하여 오류를 처리했습니다. 그러나 async/await를 사용하면 코드의 어느 곳에나 오류를 배치할 수 있으며, 그런 다음 라우터는 이러한 오류를 Express에서 제공하는 다음 함수에 전달하므로 오류 처리 흐름이 크게 단순화됩니다. 🎜🎜데이터베이스를 마이그레이션하는 데 몇 시간이 걸렸습니다. 이 방법을 사용하려면 Promise에 대한 깊은 이해와 바벨 설정 방법을 배우는 것이 필요합니다. 🎜

위 내용은 JavaScript의 Async/Await의 새로운 구문 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:webhek.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!