2016-06-02 14 views
1

トピックに関するさまざまな紹介文を読んだことがありますが、詳細はまだ分かりません(nodejs内)。asyncの詳細/ typescriptでの待ち受け

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

再び同じではありません。 eの初期化の右側を平易な数字42に置き換えると、もう一つの約束が得られます

42 
Promise { 42 } 

説明できますか?

答えて

1

async

ebより前に印刷されていると考えます。しかし、そうではありません。 bは、a(したがってbPromise)を呼び出す最終的な約束を指しています。 aeを実行しますが、yieldの結果(e = await somPromise)のみが出力されます。したがって、eは解決された値を指しています。

以下が有用である:

b Promise { <pending> } 
e 42 

詳細

を印刷

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

一部ドキュメントhttps://basarat.gitbooks.io/typescript/content/docs/async-await.html

+0

ありがとう! 3つの答えはすべて良いです。 – bollin

0

awaitを検出した場合async関数がコードしながら、一時停止それが外に続きます。

つまり、console.log(b)が実行されると、非同期機能がまだ解決されていないので、<pending>状態になります。次の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待ち)と同等です
関連する問題