상세 컨텐츠

본문 제목

[JavaScript] async를 Promise로 바꾸는 방법

카테고리 없음

by esoesmio 2024. 5. 14. 18:26

본문

async function a() {
    const a = await 1; //await이 then이다
    console.log('a', a);
    console.log('hmm');
    await null;
    const b = await Promise.resolve(1)
    console.log('b', b);
    return b;

}

a()

///axios.get()이면 그냥 axios.get().then이렇게 하면 되는데
//1 이라서 프로미스화 시켜야지 된다.Promise.resolve(1)으로.
// 프로미스 화 되야지 then이 붙는다.

Promise.resolve(1).then((a) => {
}).then((a) => {
    // const a  가 await 해서 넣는 변수니까 괄호 안에 넣으면 된다.
    console.log('a', a);
    console.log('hmm');
    return null;
}).then(() => {
    return Promise.resolve(1)
}).then((b) => {
    console.log('b', b);
    return b;

});

 

 

JavaScript에서 `async/await` 문법은 `Promise` 기반 코드를 더 읽기 쉽고 이해하기 쉽게 만드는 문법적 설탕(syntactic sugar)입니다. `async` 함수 내에서 `await` 키워드는 해당 `Promise`가 해결(resolve)될 때까지 함수의 실행을 일시 중지하고, `Promise`의 결과를 반환합니다. 이 구조를 일반 `Promise` 체인으로 변환할 때는 각 `await` 호출을 `then()` 호출로 바꾸는 방식으로 진행합니다.

### 첫 번째 예제: `async/await` 함수를 `Promise` 체인으로 변환

**원본 `async/await` 코드:**
```javascript

async function a() {
    const a = await 1;
    console.log('a', a);
    console.log('hmm');
    await null;
    const b = await Promise.resolve(1)
    console.log('b', b);
    return b;
}
a();


```

**`Promise` 체인으로 변환된 코드:**
```javascript

Promise.resolve(1)
    .then(a => {
        console.log('a', a);
        console.log('hmm');
        return null;
    })
    .then(() => {
        return Promise.resolve(1);
    })
    .then(b => {
        console.log('b', b);
        return b;
    });


```

이 변환 과정에서 각 `await` 표현은 `Promise`의 해결을 기다리는 `then()` 호출로 바뀝니다. `await 1`과 같은 표현은 JavaScript에서 즉시 해결되는 `Promise`로 변환됩니다 (`Promise.resolve(1)`). `await null`은 효과적으로 `Promise.resolve(null)`을 반환하는 것과 동일합니다.

### 두 번째 예제: 추가된 `await` 구문을 포함하여 `Promise`로 변환

**원본 `async/await` 코드:**
```javascript

async function a() {
    const a = await 1;
    console.log('a', a);
    console.log('hmm');
    await null;
    const b = await Promise.resolve(1);
    console.log('b', b);
    const c = await Promise.resolve(5);
    console.log('waeg');
    console.log('waeg');
    return b;
}
a();


```

**`Promise` 체인으로 변환된 코드:**
```javascript

Promise.resolve(1)
    .then(a => {
        console.log('a', a);
        console.log('hmm');
        return null;
    })
    .then(() => {
        return Promise.resolve(1);
    })
    .then(b => {
        console.log('b', b);
        return Promise.resolve(5);
    })
    .then(c => {
        console.log('waeg');
        console.log('waeg');
        return b; // 여기서 'b'의 값을 반환하려면 이전 스코프에서 'b'를 다루는 별도의 관리가 필요
    });


```

이 변환에서 각 `await` 호출을 `then()` 호출로 대체했습니다. 그러나 `return b;`에서 주의해야 할 점은 `b` 변수가 `then` 체인의 이전 스코프에서 정의되었기 때문에, 이 값을 반환하려면 추가적인 로직이 필요합니다. 일반적으로 이러한 경우에는 변수를 외부 스코프에 저장하거나 `then` 체인을 재구조화해야 할 수 있습니다.

이 예시들을 통해 `async/await` 구문을 일반 `Promise` 체인으로 어떻게 변환할 수 있는지 보여주었습니다. 이렇게 변환하는 주된 이유는 때로는 기존의 `Promise` 기반 라이브러리나 콜백 패턴과의 호환성을 위해서이거나, 특정 환경에서 `async/await` 문법을 지원하지 않는 경우입니다.

 

댓글 영역