15
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScript 2.1でES3/ES5コードにasync/awaitを使う

Last updated at Posted at 2017-01-26

TypeScript 2.1でターゲットがES3/ES5でも、async/awaitが使えるようになりました。
(※以前は、ES2015(ES6)ターゲットのときのみ利用可能でした。)

私は、非同期APIのテストで活用しています。

サンプルコードは以下のURLの「Downlevel Async Functions」で確認できます。
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

tsconfig.jsonでlibを追加します。

  • "dom", "es2015"
  • もしくは "dom", "es2015.promise", "es5"
tsconfig.json
{
    "compilerOptions": {
        "lib": ["dom", "es2015.promise", "es5"]
    }
}
  • 以下のサンプルの場合、Helloと出力後、500ミリ秒おきに "." が3回出力され、最後に "World!"と出力されます。
dramaticWelcome.ts
function delay(milliseconds: number) {
    return new Promise<void>(resolve => {
        setTimeout(resolve, milliseconds);
    });
}

async function dramaticWelcome() {
    console.log("Hello");

    for (let i = 0; i < 3; i++) {
        await delay(500);
        console.log(".");
    }

    console.log("World!");
}

dramaticWelcome();
15
10
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
15
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?