LoginSignup
4
2

More than 5 years have passed since last update.

Visual Studio Code - InsidersでPromise.then()構文をasync/awaitに自動変換

Last updated at Posted at 2018-10-04

Visual Studio Code - Insidersには、TypeScript 3.1が備わっています。そして、Promise().then構文を、ECMAScript 2017のasync/awaitに自動変換する機能が加わりました。

asyncが使えるのはfunctionです。Promiseオブジェクトを返すFetch APIでも自動変換できます。

コード001■fetch()でweb APIからJSONデータを取得する

function getSpacePeople_(url: string): Promise<void> {
    return fetch(url)
        .then((response) => 
            response.json()
        )
        .then((jsonData) => 
            console.log(jsonData.people)
        )
        .catch((error) => 
            console.error('エラー:', error)
        );
}
getSpacePeople_('http://api.open-notify.org/astros.json');

Visual Studio Codeで関数名をクリックすると、電球のアイコンが左端に表れます。その電球からメニューが開けますので、[Convert to async function]を選んでください(図001)。

図001■電球のアイコンから開いたメニューで[Convert to async function]を選ぶ

qiita_10_001_001.png

これですぐに、関数はasyncとされ、Promise.then()メソッドがawaitの構文に自動変換されます(図002)。また、エラーの扱いもtry/catchに変わっていることが確かめられます。

図002■async/awaitの構文に自動変換される

qiita_10_001_002.png

この自動変換の機能は、TypeScriptだけでなく、JavaScriptコードにも使えるようです。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2