2016-06-02 1 views
1

주제에 대한 다양한 소개 텍스트를 읽었지만 아직 세부 사항 (nodejs)에 어려움을 겪고 있습니다.async/typesetcript에서 기다리는 내용

async function a() { 
    const e = await Promise.resolve(42); 
    console.log(e); 
    return e; 
} 
const b = a(); 
console.log(b); 

표시

Promise { <pending> } 
42 

B와 E가 동일하게 존재하지 않는 설명은 무엇입니까? 제거가 끝나면 기다리고 있어요

Promise { 42 } 
Promise { <pending> } 

또 다시 동일하지 않습니다. 전자 초기화의 오른쪽 부분을 일반 숫자 42로 바꾸면 b에 대한 또 다른 약속이 생깁니다

42 
Promise { 42 } 

설명 할 수 있습니까?

답변

1

비동기!

eb 전에 인쇄한다고 생각합니다. 하지만 그렇지 않습니다. ba (그러므로 bPromise)을 호출하는 최종 약속을 가리 킵니다. ae을 실행하지만 yield 결과 (e = await somPromise)에서만 나타납니다. 따라서 은 확인 된 값을 가리 킵니다.

다음

도움이됩니다 :

b Promise { <pending> } 
e 42 

일부 문서 https://basarat.gitbooks.io/typescript/content/docs/async-await.html

+0

감사합니다. 3 가지 대답 모두 좋다. – bollin

0

await을 발견 할 때 async 기능은 일시 정지를 인쇄

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

, 코드 동안 그것의 바깥 쪽은 계속됩니다.

즉, console.log(b)이 실행될 때 비동기 기능이 아직 해결되지 않았으므로 상태가됩니다. 다음 tick에서 약속이 해결되면서 비동기 함수가 계속해서 42를 얻습니다.

마지막 부분에서 await은 약속이 없으므로 기능을 일시 중지하지 않으므로 바로 42를 얻습니다.

0

그것을 찾기 위해 실제 방법은 async 함수 내에서, await 후, 당신은 then

async function a(): Promise<number> { 
    const e = await Promise.resolve(42); 
    //now "in a then" 
    console.log('e',e); 
    return e; 
} 

에 있는지

function a(): Promise<number> { 
    return Promise.resolve(42) 
     //now "in a then" 
     .then(e => { 
     console.log('e',e); 
     return e; 
     }) 
} 
다소 ( await 대기) 상당이다