標籤:

【大新聞】TypeScript 支持把 async/await 編譯到 es5 了!

如題。

安裝最新的 Nightly Build:

npm install --save-dev typescript@next

然後寫一段 async/await 的代碼:

async function test() {n return await Promise.resolve(123)n}nntest().then(res => console.log(res))n

然後把目標設為 es5:

{n "compilerOptions": {n "module": "commonjs",n "target": "es5",n ...n },n ...n}n

然後能過啦!

編譯結果示例:

function test() {n return __awaiter(this, void 0, void 0, function () {n return __generator(this, function (_a) {n switch (_a.label) {n case 0: return [4 /*yield*/, Promise.resolve(123)];n case 1: return [2 /*return*/, _a.sent()];n }n });n });n}ntest().then(function (res) { return console.log(res); });nn// 公共部分:nnvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {n return new (P || (P = Promise))(function (resolve, reject) {n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }n step((generator = generator.apply(thisArg, _arguments)).next());n });n};nvar __generator = (this && this.__generator) || function (thisArg, body) {n var _ = { label: 0, sent: function() { if (sent[0] === 1) throw sent[1]; return sent[1]; }, trys: [], stack: [] }, sent, f;n function step(op) {n if (f) throw new TypeError("Generator is already executing.");n while (1) {n if (_.done) switch (op[0]) {n case 0: return { value: void 0, done: true };n case 1: case 6: throw op[1];n case 2: return { value: op[1], done: true };n }n try {n switch (f = 1, op[0]) {n case 0: case 1: sent = op; break;n case 4: return _.label++, { value: op[1], done: false };n case 7: op = _.stack.pop(), _.trys.pop(); continue;n default:n var r = _.trys.length > 0 && _.trys[_.trys.length - 1];n if (!r && (op[0] === 6 || op[0] === 2)) { _.done = 1; continue; }n if (op[0] === 3 && (!r || (op[1] > r[0] && op[1] < r[3]))) { _.label = op[1]; break; }n if (op[0] === 6 && _.label < r[1]) { _.label = r[1], sent = op; break; }n if (r && _.label < r[2]) { _.label = r[2], _.stack.push(op); break; }n if (r[2]) { _.stack.pop(); }n _.trys.pop();n continue;n }n op = body.call(thisArg, _);n }n catch (e) { op = [6, e]; }n finally { f = 0, sent = void 0; }n }n }n return {n next: function (v) { return step([0, v]); },n "throw": function (v) { return step([1, v]); },n "return": function (v) { return step([2, v]); }n };n};n

有空再來潤色文章。。


推薦閱讀:

如何進一步熟悉甚至掌握Angular?
ThinkJS 3.0 如何實現對 TypeScript 的支持
angular 和 typescript 到底是否適合最佳實踐?
如何看待 Angular 2.0 使用的 AtScript 是 TypeScript 的超集?
TypeScript 2.1中的類型運算

TAG:TypeScript | ES2015 |