29
29

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 の async/await をいますぐ使う

Last updated at Posted at 2015-09-07

基本的な考え方

  • tsc --target es6 で変換する
  • 出力したjsをさらにbabel に通して実行
$ npm install -g typescript@next
$ tsc -v
message TS6029: Version 1.6.0-dev.20150907

$ npm install -g babel

コードは Babelのasync/await試してみた(+中の処理をちょっと追ってみた) - Qiita をちょっと修正。

foo.ts
"use strict";
let wait = function(n: number){
  return new Promise(done => setTimeout(() => done(n), n));
};

let main = async function(){
  await wait(50);
  console.log('await done');
}

// async promise nomally
wait(100).then(() => console.log('promise normally done'));
main();
$ tsc -t es6 foo.ts
$ babel-node foo.js
await done
promise normally don

おまけ: typescriptの出力コードを読む

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {
    return new Promise(function (resolve, reject) {
        generator = generator.call(thisArg, _arguments);
        function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }
        function onfulfill(value) { try { step("next", value); } catch (e) { reject(e); } }
        function onreject(value) { try { step("throw", value); } catch (e) { reject(e); } }
        function step(verb, value) {
            var result = generator[verb](value);
            result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);
        }
        step("next", void 0);
    });
};
let wait = function (n) {
    return new Promise(done => setTimeout(() => done(n), n));
};
let main = function () {
    return __awaiter(this, void 0, Promise, function* () {
        yield wait(50);
        console.log('await done');
    });
};
// async promise nomally
wait(100).then(() => console.log('promise normaly done'));
main();

babelのasync/awaitのregeneratorはyieldがない環境向けにCPS変換するが、typescriptのasync/awaitはgenerator前提で__awaiterヘルパを使って(babelのと比べて)比較的単純なコードを生成する。

私見

TypeScriptは全体的に C# 感があるがMSは自分の環境に似せるための努力は怠らないという気概を感じる。とはいえ ecmascript の世界では stage: 1 なので, Object.observeを先行実装したGoogleと同じように皆自分が欲しいものを先走って作っていて若干複雑な気持ちはある。

とはいえ便利なので自分は今すぐにでも使う。

追記: 既に stage:2 になってた

thx @azu_re https://twitter.com/azu_re/status/640812872537276416

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?