your programing

JavaScript promise와 async await의 차이점은 무엇입니까?

lovepro 2020. 10. 12. 08:00
반응형

JavaScript promise와 async await의 차이점은 무엇입니까?


내 응용 프로그램 (모바일 및 웹 모두)에서 이미 (Babel 덕분에) ECMAScript 6 및 ECMAScript 7 기능을 사용 하고 있습니다.

첫 번째 단계는 분명히 ECMAScript 6 레벨이었습니다. 나는 많은 비동기 패턴, 약속 (정말 유망한), 생성기 (* 기호가 왜 있는지 확실하지 않음) 등을 배웠습니다.이 중에서 약속은 제 목적에 꽤 잘 맞았습니다. 그리고 저는 그것들을 제 애플리케이션에서 꽤 많이 사용하고 있습니다.

다음은 기본 약속을 구현 한 방법에 대한 예제 / 의사 코드입니다.

var myPromise = new Promise(
    function (resolve,reject) {
      var x = MyDataStore(myObj);
      resolve(x);
    });

myPromise.then(
  function (x) {
    init(x);
});

시간이 경과, 나는 ECMAScript를 통해 7 개 기능, 그리고 그들 존재의 하나 온 ASYNCAWAIT키워드 / 기능. 이것들은 함께 놀라운 일을합니다. 내 약속 중 일부를 async & await. 프로그래밍 스타일에 큰 가치를 더하는 것 같습니다.

다시, 여기 내 async, await 함수가 어떻게 보이는지에 대한 의사 코드가 있습니다.

async function myAsyncFunction (myObj) {
    var x = new MyDataStore(myObj);
    return await x.init();
}
var returnVal = await myAsyncFunction(obj);

구문 오류 (있는 경우)를 제쳐두고 두 가지 모두 똑같은 작업을 수행합니다. 나는 거의 대부분의 약속을 비동기로 대체 할 수있었습니다.

promise가 비슷한 작업을 수행 할 때 async, await가 필요한 이유는 무엇입니까?

async, await가 더 큰 문제를 해결합니까? 아니면 지옥 콜백에 대한 다른 해결책 이었습니까?

앞서 말했듯이 약속과 비동기를 사용할 수 있으며 동일한 문제를 해결하기를 기다립니다. async await가 해결 한 특정 사항이 있습니까?

추가 참고 사항 :

저는 React 프로젝트와 Node.js 모듈에서 async, awaits 및 promise를 광범위하게 사용했습니다. React는 특히 초기 단계였으며 많은 ECMAScript 6 및 ECMAScript 7 기능을 채택했습니다.


Promises가 비슷한 작업을 수행 할 때 async, await가 필요한 이유는 무엇입니까? async, await가 더 큰 문제를 해결합니까?

async/await단순히 비동기 코드에 동기식 느낌을줍니다. 그것은 매우 우아한 형태의 통 사적 설탕입니다.

간단한 쿼리 및 데이터 조작을 위해, 약속은 간단 할 수 있지만,이 복잡한 데이터 조작이고 이것 저것 포함 된 시나리오로 실행하면,이 코드는 단순히 경우에 무슨 일이 일어나고 있는지 이해하기 쉽게 보인다 는 동기 비록 (그것은 또 다른 방법 넣어로서, 구문 자체는 async/await주변을 둘러 볼 수있는 "부수적 복잡성"의 한 형태입니다 .

알고 싶다면 co(제너레이터와 함께) 같은 라이브러리 를 사용하여 같은 느낌을 줄 수 있습니다. 이와 같은 것은 async/await궁극적으로 (기본적으로) 해결되는 문제를 해결하기 위해 개발되었습니다 .


Async / Await는 더 복잡한 시나리오에서 훨씬 더 좋은 구문을 제공합니다. 특히 루프 또는 try/ 와 같은 다른 특정 구조를 다루는 모든 것 catch.

예를 들면 :

while (!value) {
  const intermediate = await operation1();
  value = await operation2(intermediate);
}

이 예제는 Promise를 사용하는 것만으로도 상당히 복잡 할 것입니다.


내 질문은 Promises가 비슷한 작업을 할 때 비동기가 필요한 이유는 무엇입니까? async, await가 더 큰 문제를 해결합니까? 아니면 지옥 콜백에 대한 다른 해결책 이었습니까? 앞서 말했듯이 Promises와 Async, Await를 사용하여 동일한 문제를 해결할 수 있습니다. Async Await가 해결 한 특정 사항이 있습니까?

async/ await구문 을 이해해야 할 첫 번째 사항 은 약속을 늘리기위한 구문 설탕 일뿐입니다. 사실 async함수 의 반환 값은 약속입니다. async/ await구문은 동기식으로 비동기식으로 작성할 수있는 가능성을 제공합니다. 다음은 예입니다.

Promise Chaining :

function logFetch(url) {
  return fetch(url)
    .then(response => response.text())
    .then(text => {
      console.log(text);
    }).catch(err => {
      console.error('fetch failed', err);
    });
}

Async 함수:

async function logFetch(url) {
  try {
    const response = await fetch(url);
    console.log(await response.text());
  }
  catch (err) {
    console.log('fetch failed', err);
  }
}

위의 예에서는 await프라 미스 ( fetch(url))가 해결되거나 거부 될 때까지 기다립니다 . promise가 해결되면 값이 response변수에 저장되고 promise가 거부되면 오류가 발생하여 catch블록에 들어갑니다 .

우리는 이미 async/ 를 사용하는 await것이 promise chaining보다 더 읽기 쉽다는 것을 알 수 있습니다. 이것은 우리가 사용하는 약속의 양이 증가 할 때 특히 그렇습니다. Promise chaining 및 async/ await콜백 지옥 문제를 해결하고 선택하는 방법은 개인 취향에 따라 다릅니다.


장단점과의 완전한 비교.

일반 JavaScript

  • 장점
  • 추가 라이브러리 또는 기술이 필요하지 않습니다.
  • 최고의 성능 제공
  • 타사 라이브러리와의 최고 수준의 호환성 제공
  • 임시 및 고급 알고리즘 생성 가능
  • 단점
  • 추가 코드와 비교적 복잡한 알고리즘이 필요할 수 있음

비동기 (라이브러리)

  • 장점
  • 가장 일반적인 제어 흐름 패턴 단순화
  • 여전히 콜백 기반 솔루션 임
  • 좋은 성능
  • 단점
  • 외부 종속성을 도입합니다.
  • 고급 흐름에는 여전히 충분하지 않을 수 있습니다.

약속

  • 장점
  • Greatly simplifies the most common control flow patterns
  • Robust error handling
  • Part of the ES2015 specification
  • Guarantees deferred invocation of onFulfilled and onRejected
  • Cons
  • Requires promisify callback-based APIs
  • Introduces a small performance hit

Generators

  • Pros
  • Makes non-blocking API look like a blocking one
  • Simplifies error handling
  • Part of ES2015 specification
  • Cons
  • Requires a complementary control flow library
  • Still requires callbacks or promises to implement non-sequential flows
  • Requires thunkify or promisify nongenerator-based APIs

Async await

  • Pros
  • Makes non-blocking API look like blocking
  • Clean and intuitive syntax
  • Cons
  • Requires Babel or other transpilers and some configuration to be used today

Async/await can help make your code cleaner and more readable in cases where you need complicated control flow. It also produces more debug-friendly code. And makes it possible to handle both synchronous and asynchronous errors with just try/catch.

I recently wrote this post showing the advantages of async/await over promises in some common use cases with code examples https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9


both are the ways to handle async code. But there is a difference between the execution of each. Here is the working execution -

Promise

The Promise object represents the possible completion (or failure) of an asynchronous operation and its resulting value. It is a proxy for a value not necessarily known at its creation time, and it represents the future result of an asynchronous operation.

The calling code can wait until that promise is fulfilled before executing the next step. To do so, the promise has a method named then, which accepts a function that will be invoked when the promise has been fulfilled.

Async/await

When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.

An async function can contain an await expression, which pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value

pros of async/await over promise

  • Async/await is constructed in order to give a clean syntax to the continuation semantics of asynchronous operations.
  • It avoids callback/promise hell.

참고URL : https://stackoverflow.com/questions/34401389/what-is-the-difference-between-javascript-promises-and-async-await

반응형